Binary

Posted by Monik, 18 March 2017.
Programming

Binary system, primitives in Java and bit manipulation.

Table of contents

Powers of 2

Java primitive types

Binary

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.

Adding in binary

    1 1
    0 1 1 0 = 6
  + 0 1 1 1 = 7
    -------
    1 1 0 1 = 13

Substracting in binary

                      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

Left shift («)

We move elerything to the left and fill the empty space with 0. It is equlivalent to *2:

40 « 1 = 80

Right shift (»)

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

Right logical shift (»>)

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

Important properties

Bit operations


Comments


Comments: