Search code examples
bit-manipulationbit

How is a max signed byte -1?


I am really curious and confused:

how is 0xFFFF (0b11111111111111) or 0xFF (0b11111111) -1?

if 0b01111111 is 127 and the first bit indicates that it is a positive number then shouldn't 0b11111111 be -127?

Am I missing something???


Solution

  • Two's complement form is commonly used to represent signed integers. To swap the sign of a number this way, invert all the bits and add 1. It has the advantage that there is only one representation of zero.

    01111111 = 127
    

    To get -127 flip the bits:

    10000000
    

    And add 1:

    10000001
    

    To negate 1:

    00000001 
    11111110 // flip
    11111111 // + 1
    

    With 0:

    00000000
    11111111 // flip
    00000000 // + 1 (the carry bit is discarded and it's still 0)
    

    And just to show it works going the other way:

    With -127:

    10000001
    01111110 // flip
    01111111 // + 1 and you are back to +127.