I recently inherited some Objective-C code and am really confused as to what it's actually doing?
1) I don't understand why the char byte_chars[3]
is being populated by a '0' first and then a 0 at the end?
2) I don't understand why they used unsigned char
for the wholeByte, but the put a long into it?
3) Part of me is a little confused as to what the strtol method does here, it takes 3 byte_chars bytes (which are hexadecimal), and then converts them to a long?
- (NSString *)starFromFlags:(NSString *)flags {
unsigned char wholeByte;
char byte_chars[3];
NSString *star = @"NO";
byte_chars[0] = '0';
byte_chars[1] = [flags characterAtIndex:1];
byte_chars[2] = 0;
wholeByte = strtol(byte_chars, NULL, 16);
if (wholeByte & 0x01) star = @"YES";
return star;
}
To 1:
The 0 at the end is a '\0' (both value of zero) at the end, which means "string ends here". You have to put it at the end to end the string.
The '0' (letter 0) at the begin signals a octal value (not hexadecimal, that would be "0x") for strtol()
. But as correctly mentioned by CRD (see comments), it is overriden here by the third arg passed to strtol()
. So up to here you have a two-letter string with 0 the first character and the hexadecimal representation of the flags as the second character.
The reason for this is probably, that flags contains a digit from '0' to 'f'₁₆/'F'₁₆ (0 to 15₁₀).
To 2:
Since the values that can outcome from the conversion are in the range [0…15] the long value will have one of this values. You can store it in a single byte and do not need a whole long. However, strtol()
always returns a long.
To 3:
Yes, it is a conversion from a string containing a number into a number. I.e. the string "06" will be converted to the number 6.