I have file where from I readin开发者_开发问答g the first char - meaning the first 8 bits. That is exactly what I want. My code:
char content;
char * pcontent = &content;
src_f.read(pcontent, 1);
cout << (int)content << endl; //prints -62
cout << (unsigned int)content << endl; //prints 4294967234
But: I do understand the -62. Integer can store minus values, but where did the 4294967234 come from?? I would expect some plus number smaller than 256 (because of max 8 bits..). Could you please clarify that for me?
Thx!
When you cast the content variable to an (int) or (unsigned int), you're converting it to a data type that is 32 bits wide. So the byte that you're reading in (which appears to be equal to 11000010 in binary) turns into 11111111 11111111 11111111 11000010. When this is read as an int, it equals -62, when read as an unsigned int, it equals 4294967234
As a simple example to illustrate what is going on, think of the binary representation of a negative number. The simplest way to do it would be to have the highest bit indicate the 'negative sign': 0=postive, 1=negative
0001 = 1
0011 = 3
1100 = -4
0100 = 4
1011 = -3
1111 = -7
etc
so when you convert -7 to an unsigned int, it becomes 15.
Converting -1 to an unsigned int, it becomes 9.
In reality, Two's complement is used to represent binary numbers, to prevent there being a +0 and -0.
See wiki article: http://en.wikipedia.org/wiki/Two%27s_complement
The cast is treating -62 as a 4 byte signed integer and casting that to a 4 byte unsigned integer, thus producing 2^32 - 62 as the result.
A bit of a wild guess here, but I suppose this is due to the way that your system stores integers. The max value of an unsigned integer is 4294967295. Your value is very close to that (in fact, the difference is 61). So I suppose that by converting it to an unsigned int you are using the minus sign as 2^31.
[edit]
Typo in the 2^31
The highest bit in the value is set so it's interpreted as a negative number when a signed value. That's the -62. When unsigned it's taken as a very large positive value. It's larger than 256 because you cast it to a larger binary. See "twos complement" for an in depth explanation
精彩评论