Number Representation
Computers store data in bytes.
And 1 Byte is equal to 8 bits.
So 5 in decimal is equal to 00000101 in binary. If the sign bit is 0 we call it a positive number and if the sign bit is set (or 1) we call it a negative number.
But the problem with above approach is +0 in decimal is equal to 00000000. And -0 in decimal would be equal to 10000000.
Thats why we have twos complement.
Suppose we subtract 2 from 1
0000 0001 = 10000 0010 = 2
# This operation is not possible, so we borrow a bit
1 0000 0001 = now 1 becomes (256 + 1) 0000 0010 = 2
0 1111 1111 = 255
# If the number is unsinged its 255, if its signed its -1 (as 1 - 2 = -1)So the trick here is if you want singed value of any unsgined number just subtract it with 256 (if its a byte).
Suppose if we want a twos complement (signed number) of 255. It’s 255 - 256 = -1
And the opposite is true. If we want unsigned value of any signed number we add it with 256.
Lets say we want unsinged number of -1. Its 256 + (-1) = 255
Few other things to note is a single byte is equal to 2 nibbles (4 bits each). Total values unsigned 1 byte can hold is 2^8 (0 to 2^8 -1). And for a signed byte its from - 2^7 to +2^7 -1
Also rather than doing these calculations on calculator we can use following python3 methods to make things little bit efficient.
>>> hex(0b11101110)'0xee'>>> bin(0xee)'0b11101110'>>> int(0b11101110)238