Created
December 7, 2011 16:26
-
-
Save johankool/1443455 to your computer and use it in GitHub Desktop.
Get a string representation of your NSData with or without spaces or capitals
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+Hex.h | |
// | |
// Based on code by AliSoftware | |
// http://stackoverflow.com/a/7520723/60488 | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSData (Hex) | |
- (NSString *)hexRepresentationWithSpaces:(BOOL)spaces capitals:(BOOL)capitals; | |
@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+Hex.m | |
// | |
// Based on code by AliSoftware | |
// http://stackoverflow.com/a/7520723/60488 | |
// | |
#import "NSData+Hex.h" | |
@implementation NSData (Hex) | |
- (NSString *)hexRepresentationWithSpaces:(BOOL)spaces capitals:(BOOL)capitals { | |
const unsigned char *bytes = (const unsigned char *)[self bytes]; | |
NSUInteger nbBytes = [self length]; | |
// If spaces is true, insert a space every this many input bytes (twice this many output characters). | |
static const NSUInteger spaceEveryThisManyBytes = 4UL; | |
// If spaces is true, insert a line-break instead of a space every this many spaces. | |
static const NSUInteger lineBreakEveryThisManySpaces = 4UL; | |
const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces; | |
NSUInteger strLen = 2 * nbBytes + (spaces ? nbBytes / spaceEveryThisManyBytes : 0); | |
NSMutableString *hex = [[NSMutableString alloc] initWithCapacity:strLen]; | |
for (NSUInteger i = 0; i < nbBytes; ) { | |
if (capitals) { | |
[hex appendFormat:@"%02X", bytes[i]]; | |
} else { | |
[hex appendFormat:@"%02x", bytes[i]]; | |
} | |
// We need to increment here so that the every-n-bytes computations are right. | |
++i; | |
if (spaces) { | |
if (i % lineBreakEveryThisManyBytes == 0) { | |
[hex appendString:@"\n"]; | |
} else if (i % spaceEveryThisManyBytes == 0) { | |
[hex appendString:@" "]; | |
} | |
} | |
} | |
return [hex autorelease]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment