Working with the char binary produces unexpected results

I have a file where I read the first char - this means the first 8 bits. This is exactly what I want. My code is:

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 really understand -62. An integer can store minus values, but where did the number 4294967234 come from? I expect a certain number of pluses to be less than 256 (due to max 8 bits ..). Could you clarify this for me?

thanks!

+4
source share
5 answers

When you pass a content variable to (int) or (unsigned int), you convert it to a 32-bit data type. So the byte you are reading (which appears to be 11000010 in binary) turns into 11111111 11111111 11111111 11000010. When it is read as int, it is -62, when it is read as unsigned int, it is 4294967234

+2
source

As a simple example, to illustrate what happens, think about the binary representation of a negative number. The easiest way to do this is to have the highest bit denoting a negative sign: 0 = hollow, 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 fact, Two additions are used to represent binary numbers to prevent the presence of +0 and -0.

See wiki article: http://en.wikipedia.org/wiki/Two%27s_complement

+2
source

Listing treats -62 as a 4-byte signed integer and distinguishes it to a 4-byte unsigned integer, resulting in 2 ^ 32 - 62.

+2
source

A bit of a wild guess here, but I suppose this is because your system stores integers. The maximum value of unsigned integers is 4294967295. Your value is very close to this (in fact, the difference is 61). Therefore, I believe that by converting it to unsigned int, you use the minus sign as 2 ^ 31.

[edit]

Type 2 ^ 31

+1
source

The most significant bit in the value is set in such a way that it is interpreted as a negative number with a signed value. This is -62. In the absence of a sign, it is perceived as a very large positive value. It is larger than 256 because you drop it to a larger binary. See " two-component , for a detailed explanation.

+1
source

Source: https://habr.com/ru/post/1343077/


All Articles