Skip to content

Instantly share code, notes, and snippets.

@adamkaplan
Last active March 13, 2017 08:40
Show Gist options
  • Save adamkaplan/2fddd36871dd9afb3235 to your computer and use it in GitHub Desktop.
Save adamkaplan/2fddd36871dd9afb3235 to your computer and use it in GitHub Desktop.
Print NSData As Binary
//
// NSData+JFRBinaryInspection.h
// SimpleTest
//
// Created by Adam Kaplan on 4/15/15.
//
#import <Foundation/Foundation.h>
@interface NSData (JFRBinaryInspection)
/** Returns a bit-string representation of this data, formatted as 1s and 0s grouped by 8-bits. */
- (NSString *)binaryString;
@end
//
// NSData+JFRBinaryInspection.m
// Jetfire
//
// Created by Adam Kaplan on 4/15/15.
//
#import "NSData+JFRBinaryInspection.h"
@implementation NSData (JFRBinaryInspection)
- (NSString *)binaryString {
static const unsigned char mask = 0x01;
NSMutableString *str = [NSMutableString stringWithString:
@"0 1 2 3\n"
@"01234567 89012345 67890123 45678901\n"
@"-----------------------------------\n"];
NSUInteger length = self.length;
const unsigned char* bytes = self.bytes;
for (NSUInteger offset = 0; offset < length; offset++) {
if (offset > 0) {
if (offset % 4 == 0) {
[str appendString:@"\n"];
}
else {
[str appendString:@" "];
}
}
for (char bit = 7; bit >= 0; bit--) {
if ((mask << bit) & *(bytes+offset)) {
[str appendString:@"1"];
}
else {
[str appendString:@"0"];
}
}
}
return [str copy];
}
@end
@adamkaplan
Copy link
Author

Stringifies binary data as 1s and 0s, grouped by byte (8b), with one integer (32b) per line

0          1          2           3
01234567 89012345 67890123 45678901
-----------------------------------
10000001 01000011 01111011 00100010
01101001 01100100 00100010 00111010
00100000 00100010 00110001 00101110
00110001 00101110 00110001 00100010
00101100 00100000 00100010 01100100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment