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.
Why does this code have an array of 3 bytes to build a "whole byte"?
-
05-03-2022 - |
Frage
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?
Lösung
Andere Tipps
Yes it does. strtol expects a "string". In C strings are null terminated. Thus the extra byte for the null.
C strings must be NULL (0) terminated. Since this is using a C string with a function expecting NULL terminated strings, the character array must have space for the NULL.
C strings must be NUL (0) terminated. The call to strtol function expects that.
You are messed up with C, C++ and Objective-C.
C++ and Obj-c uses full use of array. C++ creates an array of size + extra 1 space for NULL ('\0'). Obj-c has NSString class that is just a pointer, so NULL is not required.
In C you need to terminate an array of characters by NULL ('\0) and the last space is used from the allocated size. So if you write char str[10];
then you are allowed to use 9 characters and last one is automatically given to NULL.
In you code snippet you are using strtol, this is a C function which expects a C-char-array. there for last space is not used explicitly. NULL is occupying that place.