Binary system, primitives in Java and bit manipulation.
2
2^3
= 8
2^4
= 16
2^7
= 128
2^8
= 256
2^10
= 1 024
2^20
= 1 048 576
8
-bit signed two’s complement integer, minimum -128
, maximum 127
16
-bit signed two’s complement integer, minimum-32,768
, maximum 32,767
32
-bit signed two’s complement integer, minimum -2^31
, maximum 2^31-1
; from Java 8 can be used to represent an unsigned 32
-bit integer, minimum 0
, maximum value of 2^32-1
(extra method on Integer class)64
-bit two’s complement integer, minimum -2^63
, maximum 2^63-1
; from Java 8 like with int32
-bit IEEE 754 floating point64
-bit IEEE 754 floating point1
bit16
-bit Unicode character, minimum '\u0000'
(or 0
), maximum '\uffff'
(or 65 535
)0100
equals 4
- the 2^0
is on the right.
Floating point number is represented in 32
bits. The most significant bit is the sign bit, then come 8
bits of the exponent, and 23
bits of the fraction, so e.g.: 001100100.01011010110010101110001
.
1 1
0 1 1 0 = 6
+ 0 1 1 1 = 7
-------
1 1 0 1 = 13
1 / 1 / / 1
1 1 1 1 1 1
1 0 0 0 = 8 / 0 0 0 / 0 0 0 / 0 0 0
- 0 0 1 1 = 3 - 0 0 1 1 - 0 0 1 1 - 0 0 1 1
------- ------- ------- -------
? 0 1 0 1 = 5
We move elerything to the left and fill the empty space with 0
. It is equlivalent to *2
:
40
« 1
= 80
We move everything to the right and fill the empty space with 0
. It is equlivalent to /2
:
40
» 1
= 20
40
» 5
= 1
- we drop the remainder, this is integer division
Is like right shift but does not preserve the sign. So, 32th bit (2^31
, the one on the left) is the sign bit. 0
means +
, 1
means -
. In normal shift it would be overwritten after the shift, in this shift it stays, so:
-1
»> 1
= 2147483647
-1
» 1
= -1
00001000
- 1
= 00000111
0000
= x1111
= ~x0000
0000
= 0000
1111
= x0000
= x1111
= 1111
return ((num & (1 << i)) != 0)
return num | (1 << i)
return num & ~(1 << i)
return num & ((1 << i) - 1)
return num & ~((1 << i) - 1)
return num & ~(1 << i) | (v << i)
Comments: