Search code examples
iosobjective-cnsstringnsdata

NSString stringWithFormat added "ffffff"


I'm trying to get bytes from NSData and put it in NSString. While I doing this "ffffff" added simultaneously :

char *array = (char *)[deviceInfo bytes];
return [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", array[5],array[4],array[3],array[2],array[1],array[0]];

returns "53:ffffffcb:ffffffb8:51:09:fffffff0"


Solution

  • The issue relates to sign extension as the compiler promotes your signed char to unsigned int. The numbers with fffff are negative. The %x format expects an unsigned int argument.

    Declaring array correctly will fix the issue:

    const uint8_t *array = [deviceInfo bytes];