Here is a problem that involves binary numbers -
Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on.
and here is the full problem
Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on.
For example,
10101010
should be01010101
.11100010
should be11010001
.Bonus: Can you do this in one line?
Understanding the problem
I found the question confusing at first because the problem presented binary examples while describing 8 bit integers. A bit of research helped me clarify that an unsigned 8 bit integer implied integers from 0 to 255, 255 being the max binary number with 8 bits.
Furthermore, I then conflated swapping with flipping, because the first example appeared to convert all the ones to zeroes.
This problem is asking us to swap the 1st and the 2nd, the 3rd and the 4th and so on.
Solving it with brute force
An integer can be converted into its binary number by dividing it and its subsequent remainder quotients by 2. The remainder of a division by 2 is usually a 1 or a 0 and this forms our digits in the binary number
Once we store this value in an array, we can traverse this array two elements at a time in the reverse direction, while swapping and simultaneously converting it back to an integer
Solving it in one line
The question also optionally asks if we can solve this in one line
It is my suspicion, that most questions that seek a one line solution involve some sort of bit manipulation. I therefore decided to investigate this by "whiteboarding" what the bits would look like if the binary number was shifted left and right.
There was a pattern.
- When the number is shifted right - all the even binary digits correspond to our solution.
- When the number is shifted left - all the odd binary digits correspond to our solution
It seems like I was on the right track
In order to pick certain digits in a binary number we can use a mask. A binary mask is simply a binary number, where the ones represent the digits we want. All other digits are set to zero.
For example a mask of "101" will pick whatever digit is in the first and last position while the second digit is set to zero.
101 & 100 will produce 100. Each corresponding digit undergoes the '&' operation
Shifting the number and applying the appropriate masks gives us two numbers that can be combined with an "or" operation to give us the expected result. The or operation "adds" our two numbers together