diff options
Diffstat (limited to 'Source/SPDataAdditions.m')
-rw-r--r-- | Source/SPDataAdditions.m | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/Source/SPDataAdditions.m b/Source/SPDataAdditions.m index 166288e5..ec91f55c 100644 --- a/Source/SPDataAdditions.m +++ b/Source/SPDataAdditions.m @@ -100,6 +100,92 @@ static char base64encodingTable[64] = { return base64; } +- (NSString *)dataToFormattedHexString +/* + returns the hex representation of the given data + */ +{ + unsigned i; + unsigned totalLength = [self length]; + int bytesPerLine = 16; + NSMutableString *retVal = [NSMutableString string]; + char *nodisplay = "\t\n\r\f"; + + // get the length of the longest location + int longest = [(NSString *)[NSString stringWithFormat:@"%X", totalLength - ( totalLength % bytesPerLine )] length]; + + for ( i = 0; i < totalLength; i += bytesPerLine ) { + int j; + NSMutableString *hex = [[NSMutableString alloc] initWithCapacity:(3 * bytesPerLine - 1)]; + NSMutableString *location = [[NSMutableString alloc] initWithCapacity:(longest + 2)]; + NSMutableString *chars = [[NSMutableString alloc] init]; + unsigned char *buffer; + int buffLength = bytesPerLine; + + // add hex value of location + [location appendString:[NSString stringWithFormat:@"%X", i]]; + + // pad it + while( longest > [location length] ) { + [location insertString:@"0" atIndex:0]; + } + + // get the chars from the NSData obj + if ( i + buffLength >= totalLength ) { + buffLength = totalLength - i; + } + buffer = (unsigned char*) malloc( sizeof( unsigned char ) * buffLength ); + NSRange range = { i, buffLength }; + [self getBytes:buffer range:range]; + + // build the hex string + for ( j = 0; j < buffLength; j++ ) { + unsigned char byte = *(buffer + j); + if ( byte < 16 ) { + [hex appendString:@"0"]; + } + [hex appendString:[NSString stringWithFormat:@"%X", byte]]; + [hex appendString:@" "]; + + // if the char is undisplayable, replace it with "." + unsigned char current; + int count = 0; + while ( ( current = *(nodisplay + count++) ) > 0 ) { + if ( current == byte ) { + *(buffer + j) = '.'; + break; + } + } + } + + // add padding to missing hex values. + for ( j = 0; j < bytesPerLine - buffLength; j++ ) { + [hex appendString:@" "]; + } + + // remove extra ghost characters + [chars appendString:[NSString stringWithCString:(char *)buffer]]; + if ( [chars length] > bytesPerLine ) { + [chars deleteCharactersInRange:NSMakeRange( bytesPerLine, [chars length] - bytesPerLine )]; + } + + // build line + [retVal appendString:location]; + [retVal appendString:@" "]; + [retVal appendString:hex]; + [retVal appendString:@" "]; + [retVal appendString:chars]; + [retVal appendString:@"\n"]; + + // clean up + [hex release]; + [chars release]; + [location release]; + free( buffer ); + } + + return retVal; +} @end |