Tag Info

For challenges involving bitwise commands or manipulation of numbers at the bit level

This challenge involves doing something on the bit level, whether it be counting the number of bits or some other bitwise operation.

Standard bitwise operators:

• &, the bitwise and. This operator looks at the two numbers bit by bit and if and only if both numbers have a 1 at the same bit, the output will also have a 1 at that bit. For example:

  100100100100100 & 101010101010101 is

100100100100100
& 101010101010101
------------------
100000100000100

• |, the bitwise or. This operator looks at the two numbers bit by bit and if at least one number's bit is 1, the output will have a 1 at that point. Example:

  100100100100100 | 101010101010101 is

100100100100100
| 101010101010101
------------------
101110101110101

• ^, the bitwise xor. This operator looks at the two numbers bit by bit and if and only if both numbers' bit are not the same, the output will have a 1 at that bit. Example:

  100100100100100 ^ 101010101010101 is

100100100100100
^ 101010101010101
------------------
001110001110001

• ~, the bitwise not. This unary operator flips the bits of a number. Example:

  ~100001000100101 = 011110111011010

• <<, >>, >>> bitshifts. These shift a number left or right, depending on the number to the right of the operator. Bits shifted past the edge of the number are lost. $$\x\$$ << $$\y\$$ is just a fancy way (much faster way) of multiplying $$\x\$$ by $$\2^y\$$. For example:

  100100100100100 << 5 = 010010010000000

100100100100100
001001001001000
010010010010000
100100100100000
001001001000000
010010010000000


>> and >>> differ only for negative integers. The both divide $$\x\$$ by $$\2^y\$$. >>> works like so:

  100100100100100 (18724) >>> 5 = 000001001001001  (585)

100100100100100
010010010010010
001001001001001
000100100100100
000010010010010
000001001001001


>>'s only difference is with signed integers. Your computer represents negative numbers in two's complement. This means that for negative numbers, we start counting at all 1s for negative one, and count upwards by using 0s (please see Wikipedia article for better explanation). With >>, the leftmost bit (i.e. the sign bit) is used to fill the rest of the number. Example:

  100100100100100 (-14044) >> 5 = 111111001001001  (-439)

100100100100100
110010010010010
111001001001001
111100100100100
111110010010010
111111001001001