Prev:
Bitwise Operators: AND OR XOR
Next:
Bitwise NOT (Complement)
Bitwise Left-Shift is useful when to want to MULTIPLY an integer (not floating point numbers) by a power of 2.
The operator, like many others, takes 2 operands like this:
a << b
This expression returns the value of a multiplied by 2 to the power of b.
Why is it called a left shift?
Answer: Take the binary representation of a, and add b number of zeros to the right, consequently "shifting" all the bits b places to the left.
Example: 4 << 2.
4 is 100 in binary. Adding 2 zeros to the end gives 10000, which is 16, i.e.
4*22 = 4*4 = 16.
What is 4 << 3 ? Simply add 3 zeros to get 100000, which is 4*23 = 4*8 = 32.
Notice that shifting once to the left multiplies the number by 2. Multiple shifts of 1 to the left, results in multiplying the number by 2 over and over again. In other words, multiplying by a power of 2.
More examples:
5 << 3 = 5*23 = 5*8 = 40
8 << 4 = 8*24 = 8*16 = 128
1 << 2 = 1*22 = 1*4 = 4
Bitwise shifts are said to be more efficient than the normal arithmetic operations, but I'm still yet to write a computer game :)
Bitwise shifting of negative numbers requires knowledge of the binary representation of negative numbers.
More space for your calculations:
Bitwise Right-Shift does the opposite, and takes away bits on the right.
Suppose we had:
a >> b
This expression returns the value of a divided by 2 to the power of b.
Example: 8 >> 2.
8 is 1000 in binary. Performing a right shift of 2 involves knocking the last 2 bits off: 1000, which leaves us with 10, i.e.
2.
8 >> 2 is the as doing 8 / 22 = 8 / 4 = 2.
But what happens if we had a left operand that's not a power of 2? Let's try 9 >> 2.
9 is 1001. Now take off the last 2 bits, leaving us with 10, which is 2. But this does make sense, since 9 / 4 = 2.25,
which rounds down to 2.
Another example: 29 >> 3.
29 is 11101 in binary. Take of the last 3 bits to leave 11, which is 3 in decimal. Check: 29 / 8 is 3.625, which rounds
down to 3, so we're okay :)
More space for your calculations:
Prev:
Bitwise Operators: AND OR XOR
Next:
Bitwise NOT (Complement)
www.iota-six.co.uk
Copyright © 2001-2003
Unauthorized copying not permitted
Designed and Developed Using Macromedia Studio MX