﻿ Left shift ﻿

Main Page

# Left shift

Bit from First Number Bit from Second Number
Result
1
1
0
1
0
1
0
1
1
0
0
0
To XOR the numbers 25 and 3 together, use the following code:
var iResult = 25 ^ 3;
The result of a bitwise XOR between 25 and 3 is 26:
25 = 0000 0000 0000 0000 0000 0000 0001 1001
2 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
XOR = 0000 0000 0000 0000 0000 0000 0001 1010
As you can see, four bits contain 1 in either number, so these are passed through to the result. The binary
code 11010 is equal to 26.
Left shift
The left shift is represented by two
less-than
signs (
<<
). It shifts all bits in a number to the left by the
number of positions given. For example, if you take the number 2 (which is equal to 10 in binary) and
shifted it 5 bits to the left, you end up with 64 (which is equal to 1000000 in binary):
var iOld = 2; //equal to binary 10
var iNew = iOld << 5; //equal to binary 1000000 which is decimal 64
Note that when the bits are shifted, five empty bits remain to the right of the number. The left shift fills
these bits with the value in the 32nd bit (the sign bit) to make the result a complete 32-bit number
(Figure 2-6).
Figure 2-6
00000000000000000000000000000010
The number 2
"Secret" sign bit
00000000000000000000000001000000
The number 2 shifted to the left 5 bits (the number 64)