CS Student
CS Student

Reputation: 1633

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.

Upvotes: 0

Views: 259

Answers (2)

user395760
user395760

Reputation:

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. 231 is the value of the MSB (because the LSB has value 20), so the correct value is the sum 20 + ... + 230 = 231-1.

Upvotes: 2

Paul92
Paul92

Reputation: 9062

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).

Upvotes: 1

Related Questions