Question

I'm trying to convert a line of hex to a line of char values. This is the code I use:

// Store HEX values in a mutable string:
    NSUInteger capacity = [data length] * 2;
    NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
    const unsigned char *dataBuffer = [data bytes];
    NSInteger i;
    for (i=0; i<[data length]; ++i) {
        [stringBuffer appendFormat:@"%02X ", (NSUInteger)dataBuffer[i]];
    }
// Log it:
  NSLog(@"stringBuffer is %@",stringBuffer);


// Convert string from HEX to char values:
NSMutableString * newString = [[NSMutableString alloc] init];
NSScanner *scanner = [[NSScanner alloc] initWithString:content];
unsigned value;
while([scanner scanHexInt:&value]) {
    [newString appendFormat:@"%c ",(char)(value & 0xFF)];
}
NSLog(@"newString is %@", newString);

This works great, so far. The output received it as expected:

String Buffer is 3D 3E 2C 01 2C 31 33 30 37 31 38 30 39 32 34 2D 30 37 2C FF 00 00 00 00 00
 newString is = > ,  , 1 3 0 7 1 8 0 9 2 4 - 0 7 , ˇ

There is just one problem, the NULL values are terminating my string (I think). New string should type "0 0 0 0", but it doesn't, it just ends there. I think it is ending there because 3 zeros in a row = NULL in char. Does anyone know how I can prevent this string from terminating and display the entire value?

Was it helpful?

Solution

The %c format does not produce any output for the NULL character, but is does also not terminate the string. See the following example:

NSMutableString * newString = [[NSMutableString alloc] init];
[newString appendFormat:@"%c", 0x30]; // the '0' character
[newString appendFormat:@"%c", 0x00]; // the NULL character
[newString appendFormat:@"%c", 0x31]; // the '1' character
NSLog(@"newString is %@", newString);
// Output: newString is 01
NSLog(@"length is %ld", newString.length);
// Output: length is 2

So you can not expect to get any output for the hex input 00. In particular, you can not expect to get the character "0" because that has the ASCII code hex 30, not 00.

Note that you can convert NSData to NSString directly using

NSString *s = [[NSString alloc] initWithData:data encoding:encoding];

if data represents a string in some encoding, e.g. UTF-8 (which is not the case with your data).

A better answer might be possible if you explain what the data represents and what string representation of the data you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top