JaVa
   

Bit Manipulation

In order to understand how to manipulate bits, you must first understand how numbers of the decimal notation, those numbers that we are used to using, are stored in the binary notation. The following table shows a list of decimal numbers and their binary representations.

Decimal

Binary

0

0

1

1

2

10

3

11

4

100

5

101

11

1011

15

1111

212

11010100

Decimal numbers are base 10 numbers, whereas binary numbers are base 2. If we look at how we perceive the value of a decimal number, we can then understand how to convert these numbers to their binary notation. So imagine the following number: 574. We know what this number is because it is familiar to us, but we can also look upon its value in the following way.

Base 10n

102

101

100

Value

100

10

1

Note that just in case you don't understand the term 102, it translates as 10 * 10, equaling 100. So, for example, 105 would be 10 * 10 * 10 * 10 * 10, equaling 100000, and 43 would be 4 * 4 * 4, equaling 64. We can then look at the value of 574 in the following way as a decimal notation:

(102 * 5) + (101 * 7) + (100 * 4) = 500 + 70 + 4 = 574


This is a bit pointless but only because our perception of the value in the decimal notation is immediately understandable. Now take the following table:

Base 2n

22

21

20

Value

4

2

1

Now the binary base is 2 and the decimal base is 10. This means that decimal values range from 0 to 9 and binary values range from 0 to 1. So the binary value 101 can be worked out in the following way, similar to the way we looked at the decimal notation:

(22 * 1) + (21 * 0) + (20 * 1) = 4 + 0 + 1 = 5


If we look back to the decimal/binary table on the previous page, we can now work out the larger bit value of 11010100 as follows:

(27 * 1) + (26 * 1) + (25 * 0) + (24 * 1) + (23 * 0) + (22 * 1) + (21 * 0) + (20 * 0) =
128 + 64 + 0 + 16 + 0 + 4 + 0 + 0 =
212


JaVa
   
Comments