Skip to content

Instantly share code, notes, and snippets.

@esutton
Last active February 28, 2024 06:46
Show Gist options
  • Save esutton/02700ae5c9a6affcd34e477799ef69b3 to your computer and use it in GitHub Desktop.
Save esutton/02700ae5c9a6affcd34e477799ef69b3 to your computer and use it in GitHub Desktop.
Print a string buffer in hex 16-bytes per row in Objective C
// debugDumpHexBytes.h
#ifndef DebugHelper_h
#define DebugHelper_h
#import <Foundation/Foundation.h>
#ifdef NDEBUG
// do nothing
#define DbgLog(...)
#else
#define DbgLog NSLog
#endif
@interface DebugHelper : NSObject
+ (void)debugDumpPointerHexBytes:(const char*)source withLength:(int)length;
+ (void)debugDumpHexBytes:(NSData *)data withLength:(int)length;
+ (void)debugDumpHexBytes:(NSData *)data;
@end
#endif /* DebugHelper_h */
// debugDumpHexBytes.m
#import <Foundation/Foundation.h>
#import "debugDumpHexBytes.h"
@implementation DebugHelper
+ (void)debugDumpPointerHexBytes:(const char*)source withLength:(int)length {
DbgLog(@"------------------------");
int offset = 0;
int row = 0;
NSMutableString *line = [[NSMutableString alloc]init];
while(length > offset ) {
[line setString:[NSString stringWithFormat:@"%04x: ", offset]];
for(int i = 0; i < 16; ++i) {
if(8 == i) {
[line appendString:@" "];
}
uint8_t value = source[offset++];
[line appendString:[NSString stringWithFormat:@"%02x ", value]];
if(length == offset) {
break;
}
}
DbgLog(@"%@\n", line);
++row;
}
DbgLog(@"........................");
}
+ (void)debugDumpHexBytes:(NSData *)data withLength:(int)length {
const char* source = (const char*)[data bytes];
[self debugDumpPointerHexBytes:source withLength:length];
}
/// Debug dump bytes in hexadecimal format 16-bytes per row
///
/// \param source
/// \param length
///
/// Example Output:
/// \code
/// 0000 bd 7a 32 13 08 1c 1e d9 - c9 48 48 0b 5f 23 1a f5
/// 0010 72 3d 8f 7a e6 2c 07 e4 - 6e 45 79 0f cb 18 13 6f
/// \endcode
+ (void)debugDumpHexBytes:(NSData *)data {
[self debugDumpHexBytes:data withLength:(int)[data length]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment