What is f-ing my data?
I'm getting a NSData *
and trying to get it byte by byte but the data is filled with f
.
NSData *Data = getData();
cout << "The log way:" << endl;
NSLog(@"%@", Data);
cout << "The data way:" << endl;
char *data = (char *)[Data bytes];
for(int i = 0; i < [Data length]; i++)
{
cout.width(2);
cout.fill(0);
cout << hex << (int)(data[i])开发者_Go百科 << " ";
}
cout << endl;
What I'm getting as output:
The log way:
/* something long about time and file */<1f9cb0f8>
The data way:
1f ffffff9c ffffffb0 fffffff8
How can I get this data as int
s without all those f
?
The char
data type is of undefined signedness, and it seems your compiler (gcc or clang?) decided it should be signed. Therefore, when you cast a char
to a larger type, sign extension is used, which fills the extra bits with the same value the most significant bit has. For bytes with a value larger than 0x7F
, the most significant bit is set, so it breaks the enlargement.
What you want is zero extension, which zeroes the extra bits. You can get it by using the unsigned char
type.
This should do it:
unsigned char *data = (unsigned char *)[Data bytes];
By the way, -[NSData bytes]
return a const
pointer. You should honor this and mark your pointer as const
too:
const unsigned char *data = (const unsigned char *)[Data bytes];
That is data as ints, sort of. The data is split into bytes and sign-extended to ints. As bytes, your data is 1f 9c b0 f8
. 9c
, b0
, and f8
are all negative, so they are sign extended by making the extra bits all 1, which is why you are getting a bunch of f
s.
精彩评论