简体   繁体   中英

Binary representation of data types in C

If I have a normal 32 bit int in C, how is the number represented in memory? Specifically, how is the sign stored?

At first I thought it would be sign and magnitude but then I remembered there would be + and - 0, so then I thought it could be stored in two's complement, however when using two's complement I ended up getting a maximum value of 4294967293 with the MSB set to 0 (I got this value by summing up everything from 2^31 to 2^0) which as we all know is wrong.

The C standard doesn't mandate two's complement, but it's by far the most common option (and I think even this is an understatement). The reason you arrive a 4 billion something, not at the correct INT_MAX , is an off-by-one error: You added the 32th bit as well. 2 31 is the value of the MSB (because the LSB has value 2 0 ), so the correct value is the sum 2 0 + ... + 2 30 = 2 31 -1.

Even this is implementation defined, most machines use two's complement.

The problem is that your computation is wrong. Summing up 2^0 to 2^31 (which is 2^32 - 1, by the way) means that you use 32 bits. This is not correct: only 31 bits are used for the actual number. MSB has a special meaning and it has to do with the sign (is not really 'the sign'). So, you need to sum up from 2^0 to 2^30 (which is 2^31 - 1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM