`
Computers store numbers in binary format. For example, the number 35110 is represented as 00000001010111112. This is because, at their core, computers are electronic devices. It’s simpler to represent the binary output of electronic circuits, where the presence of electricity in a wire signifies “true” and its absence signifies “false.”
The diagram below illustrates that a wire with a voltage between 0 and 0.5 volts is interpreted as a 0, whereas a voltage around 5 volts is read as a 1. This range is designed to accommodate potential noise and inaccuracies in the wiring.
Byte = 8 bits (binary digits)
Example: 001010112 = 32+8+2+1 (0X27+0X26+1X25+0X24+1X23+0X22+1X21+1X20) = 4310
Example: 2610 = 16+8+2 = 001010102
Hexadecimal is a base-16 numbering system where 1 byte is represented by 2 hexadecimal digits. It uses the digits 0 to 9 and the letters A to F (with A representing 10 and F representing 15). In C, hexadecimal numbers are prefixed with 0x, so FA1D37B16 should be written as 0xFA1D37B or 0xfa1d37b.
Hex | Decimal | Binary | | | Hex | Decimal | Binary |
---|---|---|---|---|---|---|
0 | 0 | 0000 | | | 8 | 8 | 1000 |
1 | 1 | 0001 | | | 9 | 9 | 1001 |
2 | 2 | 0010 | | | A | 10 | 1010 |
3 | 3 | 0011 | | | B | 11 | 1011 |
4 | 4 | 0100 | | | C | 12 | 1100 |
5 | 5 | 0101 | | | D | 13 | 1101 |
6 | 6 | 0110 | | | E | 14 | 1110 |
7 | 7 | 0111 | | | F | 15 | 1111 |
Use the high order bit to indicate negative: call it the “sign bit”. Ex:
0x00 = 000000002 is non-negative, because the sign bit is 0
0x7F = 011111112 is non-negative
0x85 = 100001012 is negative
How to represent a negative number. One approach could be, just keep 1 at MSB. As illustrated in below image:
As we can see, 410=01002 and hence -410=11002
But this approach is failing basic arithmatic operations like 4-4=0 and also 0000=0 and 1000 is -0. There is nothing like -0.
2’s Complement:
It can be calculated by adding 1 to 1’s complement. 1’s complement is flipping all the bits (~ operator)
So, -n = ~n + 1
Benefits of using 2’s complement for negative numbers.
int findLonelyNumber(int[] a){
int result = 0;
for(int t : a){
result ^= t;
}
return result;
}
interestingly, when guest says she wants tea or coffee, she does not mean host to bring both. Actually, she meant “I want tea xor coffee”.
A float has 3 part when stored by computer. sign, exponent and factor which can be interpreted as (sign)1XFX2E-127 In 4 byte float, MSB is sign bit followed with 8 bits of Exponent and remaining 23 bits of Factor.
ex: 11000001001100000000000000000000 = -1 X 1.375 X 2 129-127 = 5.5
Note: factor is calculated by : 1 + 0X1/2 + 1X1/4 + 1X1/8