Search code examples
binarysigned

Identifying positve and negative numbers by looking at it's binary form


New to the world of programming, I was reading one of the chapters in the beginning of Java: The Complete Reference which was Bitwise operators and the book explained how are negative numbers stored. It said, for example -42 is represented by inverting all the bits of 42 i.e. 00101010, yielding 11010101 then adding 1 to it finally resulting 11010110. It said due to the same reason there is no -0 as it cannot be stored as it is 100000000 will exceed the capacity to be stored in the 1 byte.

The only thing that I cannot understand how would the computer understand whether it's a signed or unsigned number because though 11010101 is -42 but it can also be 213.


Solution

  • If you don't say what number representation system is being used, it is not possible to say whether a bit pattern is negative or positive by looking at the bit patterns. (Obviously!)

    But if you are talking about two's complement binary integers AND you know which bit is the most significant one, then a positive number has the most significant bit 0.

    For example:

    • Assuming that 11010110 is a two's complement 8 bit number, and the leftmost bit is the most significant one, then that represents a negative number.

    • But if 11010110 was actually the least significant 8 bits of the 16 bit number 0000000011010110, then that represents a positive number.

    As you can see, it is important to know how many bits there are in the number representation scheme you are using!


    It said due to the same reason there is no -0 as it cannot be stored as it is 100000000.

    Well ... sort of. A better reason is that an N-bit two's complement representation has values from -2N-1 to +2N-1 - 1. If you count them there are precisely 2N values in that range, leaving no room for a -0 value.

    If you really want to understand this stuff about number representations properly, you need to also understand how two's complement relates to other ways of representing signed integers; see Signed Number Representations.

    It is worth noting that modern computer hardware uses 2's complement exclusively for integer representations. Dealing with distinct -0 and +0 values makes things complicated for both hardware and software.