Last active
March 13, 2017 08:40
-
-
Save adamkaplan/2fddd36871dd9afb3235 to your computer and use it in GitHub Desktop.
Print NSData As Binary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Stringifies binary data as 1s and 0s, grouped by byte (8b), with one integer (32b) per line