0

So my question may be very basic. But I am pretty new to computers.

If there are 32 bits in the int data type then it means there are 32 places where we can write either a zero or a one (if I am understanding it right). So if this range is to be divided into negative and positive should it not be half of 32 on the left and the other half on the right?

2 Answers 2

0

We are talking about a signed integer (i.e. an integer that has a plus or minus sign and because of that it can contain both positive and negative numbers).

The sign itself occupies one bit - usually the left one (the very first bit in the 32bit array of bits). If that bit is zero then the remaining 31bits represent a positive number (or zero - if all bits are zero). If the first bit is 1 then the remaining 31bits represent a negative number. This is just a format - essentially an agreement of what each bit will be representing.

If one bit is taken to represent the sign then you only have 31bits remaining to contain the actual values - hence 2^31

Recall that 2^32 divided by 2 (i.e. taking a half) is 2^32/2 = 2^32/2^1 = 2^(32-1) = 2^31

0

@dmitryK is on the right track, mostly, except that negative numbers aren't directly represented by their absolute values. It's more complicated than just throwing a sign bit in.

If you really want to know the ins and outs of how a signed integer is represented, google "two's complement". It's easier to point you to an existing explanation than to explain it here.

Here's a good, simple explanation: https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

Also, thinking about your statement, "So if this range is to be divided into negative and positive should it not be half of 32 on the left and the other half on the right?'", there a problem with that. Where do you account for the zero value, on the left or the right? two's complement handles that nicely, and explains why one side has to lose one value.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .