User:Fabien Labeyrie/Bit Shifting

From XPUB & Lens-Based wiki


Bit Shifting : how i learned to stop worrying and love binary numbers

Here is how to deal with binary numbers when you are programming on an old computer (Basic V 2.0 on Commodore 64) or when you are configuring internal parameters on your arduino board. Thanks to Mr. Stock who made this nightmare look nearly simple.


What is << (bit shifting) ?

In the binary numeral system, everything looks like 0110010100010100111...
A bit shift consists in moving one or several digits in a line of 0110010100010100111...

Examples


1 << 3

1 = 0001 in the binary numeral system
1 << 3 means we are gonna move the value 1, to the left <<, 3 times.
1 << 3 : 0001  ->  0010  ->  0100  ->  1000   
               1st move  2nd move  3rd move

1 << 3 = 1000 and 1000 in the binary numeral system = 8

7 << 5

7 = 00000111
7 << 5 : 0000 0111  ->  0000 1110  ->  0001 1100  ->  0011 1000  ->  0111 0000  ->  1110 0000 

7 << 5 = 1110000 in the binary numeral system = 224


The best is yet to come

The nibble

Big endian Vs little endian

Logical operations

Bits and modulo