Daily Coding Problem: Problem #1780 [Medium]

Problem statement

This problem was asked by Cisco.

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 be 01010101. 11100010 should be 11010001.

Bonus: Can you do this in one line?


This is simple enough that I’ll show the entire solution:

package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
)

func main() {

	n, err := strconv.ParseUint(os.Args[1], 2, 8)
	if err != nil {
		log.Fatal(err)
	}

	x := uint8(n)
	even := x & 0b01010101
	odd := x & 0b10101010
	swapped := (even << 1) | (odd >> 1)

	fmt.Printf("original: %08b\n", x)
	fmt.Printf("swapped:  %08b\n", swapped)

    swapped = ((x & 0b01010101) << 1) | ((x & 0b10101010) >> 1)
        
    fmt.Printf("swapped:  %08b\n", swapped)
}

I do not see how this rates a “[Medium]”. Solving this involves knowing how to mask bits with binary-and, put bits together with binary-or, and shift bits both left and right. That’s it, except for remembering that >> and << shift bits, not roll them.

I can’t imagine that this gets an interviewer any knowledge about a candidate’s coding skill, except whether they can do bitwise operations. I suppose the interviewer could get operation priority knowledge out of a candidate by getting them to remove parentheses in the one liner.

Since I didn’t know what operation priorities are involved, I tried removing all parentheses from the one-liner:

    swapped = x&0b01010101<<1 | x&0b10101010>>1

It works as desired without parentheses. I’ve held the belief that if I have some questions about order of operations, I should parenthesize whatever complicated expression I’m writing so that upon re-reading, I can immediately see what’s desired.

Maybe a candidate could boost this sorry problem by suggesting other test cases, perhaps to see if shifting a bit off the left or right of the 8-bit value works correctly.

Ha, ha, I did this one a long time ago, and forgot about it, so I did it again. I did it as Daily coding problem #693, October 2020. I even did it somewhat differently back then.

Github repo

October 2020 Github repo