Search This Blog

Showing posts with label bit shifting. Show all posts
Showing posts with label bit shifting. Show all posts

Saturday, 21 February 2015

Numeral systems and bit shifting quick overview

Numeral Systems


Numeral system Radix/root Digits Example In Decimal system
Binary

0,1 0,1

Byte 2

Groupings of 8 binary digits
(representation of a byte or integer (16/32/64 bits))
01010001 (02 × 27) + (12 × 26) + (02 × 25) + (12 × 24) + (03 × 23) + (02 × 22) + (02 × 21) + (12 × 20)
Decimal 10

0-9 124 (110 × 102) + (210 × 101) + (410 × 100)
Octal 8

0-7 02732 (28 × 83) + (78 × 82) + (38 × 81) + (28 × 80)
Hexadecimal 16

0-9,A-F (corresponding to 10-15) 0x2AF3 (216 × 163) + (A16 × 162) + (F16 × 161) + (316 × 160)

Bit Shifting

 

128
64 32 16 8 4 2 1

27         

26

25

24

23

22

21

20

0 1 0 1 0 0 0 1



0     1   0    1    0   0  0   1 => 1*64 + 1*16 + 1*1 = 81

 

 

Arithmetic bit shifting to the right with >>

 


Makes bits fall of the right and adds zero padding to the left. This is equivalent to arithmetic division.

01010001 = 1*64 + 1*16 + 1*1 = 81

$y =  0b01010001 >> 1
>> 1 … shifting by one position to the right:
01010001 → 00101000 = 1*32 + 1*8 = 40   (ie int(81/2))

Arithmetic bit shifting to the left with <<


Makes bits fall of the left and adds zero padding to the right. This is equivalent to arithmetic multiplication by 2 to the number on the right of the operator.

01010001 = 1*64 + 1*16 + 1*1 = 81

$y =  0b01010001 << 1

<< 1 … shifting by one position to the left, we are multiplying by 2 to 1:
01010001 → 10100010 = 1*128 + 1*32 + 1*2 = 162 (ie 81 * 2)


NOTE

 

The number of shift positions needs to result in a value within the allowed range of the original value type:

Wrong:

<< 2:
01010001 (81) → 01000100 = 1*64 + 1*4 =68