I found the following code on the internet, it converts NSString
representations such as
@"00F04100002712"
into an actual array of bytes. The code works and does generate the correct output; I just don't understand why there is char byte_chars[3]
instead of char byte_chars[2]
since only the first two positions are used in the code.
void hexStringToBytes(NSString *s, NSMutableData *data)
{
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int commandLength = (int)[s length];
// convert hex values to bytes
for (int i=0; i < commandLength/2; i++)
{
byte_chars[0] = [s characterAtIndex:i*2];
byte_chars[1] = [s characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[data appendBytes:&whole_byte length:1];
}
}
I think it has something to do with the strtol
function call but I am not sure what.
Can someone explain how and why this works?
C style strings have a terminating zero (aka null) character. An ASCII representation of an 8 bit byte in hexadecimal will be two characters plus that terminator.