Trouble converting Dec to Hex (Int to Char)
i know this seems to be a stupid question, but i'm really getting trouble here.
I'm working in a project where i have some functions i can´t modify. That is, i got some C functions (not really my speciality) inside my Obj. C code that i can modify.
So here it is... to explain a little what i have.
I'm receiving a NSData like "\xce\x2d\x1e\x08\x08\xff\x7f
" . I have to put each \hex code in a char array, like this:
cArray[1]=ce;
cArray[2]=2d;
cArray[3]=1e;
cArray[4]=08;
etc, etc... of course not LIKE THIS, but just so you understand. My initial move was to separe the NSData with subdataWithRange: and fill in an array with all "subdata". So the next move could be passing each position of that array to a char array, and that's where i got stuck.
I'm using something like (dont have my code right now)
for(int i=0 ; i<=64 ; i++) {
[[arrayOfSubData objectAtIndex:i] getBytes:&charArray[i]];
}
To fill the char array with the hex from my array of subData. That works almost perfectly. Almost.
Taking that example of cArray, my NSLog(@"pos%i: %x",i,charArray[i])
would show me:
pos1: ce
pos2: 2d
pos3: 1e
pos4: 8
And all the "left zeros" are supressed in that same way. My workaround for the moment (and i´m not sure if it is the best practice here) is to take my subDataArray and initWithFormat:
a string with it. With that i can transform the string 开发者_StackOverflow中文版to an int with NSScanner scanHexInt:
, but then i´m stucked again when converting back my decimal int to a hexadecimal CHAR. What would be the best approach to fill my char array that way?
Any help or some "tough love" will be greatly appreciated. Thanks
According to the normal rules of printf formatting (which NSLog follows also) you want the following:
NSLog(@"pos%i: %02x", i, charArray[i]);
The '0' says to left pad with 0s and is a flag. The '2' says to ensure that output for that field is at least two characters. So that'll ensure that at least two characters are output and pad to the left with '0's in order to fill space.
精彩评论