How to swap all odd and even bits in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strconv"
)

// swapsOddAndEvenBits swaps odd and even bits in a 32-bit unsigned integer.
// For example, bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc.
func swapsOddAndEvenBits(n uint32) uint32 {
    // Mask to isolate odd bits: binary 101010... (hex: 0xAAAAAAAA)
    oddBits := n & 0xAAAAAAAA

    // Mask to isolate even bits: binary 010101... (hex: 0x55555555)
    evenBits := n & 0x55555555

    fmt.Println("oddBits:", toBitString(oddBits, 8))
    fmt.Println("evenBits:", toBitString(evenBits, 8))

    // Shift odd bits right to move them to even positions
    oddBits >>= 1

    // Shift even bits left to move them to odd positions
    evenBits <<= 1

    fmt.Println("oddBits Right-shift:", toBitString(oddBits, 8))
    fmt.Println("evenBits Left-shift:", toBitString(evenBits, 8))

    // Combine the shifted bits
    return oddBits | evenBits
}

// toBitString converts a number to a binary string with fixed width.
// Pads with leading zeros to match the desired bit width.
func toBitString(n uint32, width int) string {
    bits := strconv.FormatUint(uint64(n), 2)
    if len(bits) < width {
        return fmt.Sprintf("%0*s", width, bits)
    }
    return bits[len(bits)-width:]
}

func main() {
    var n uint32 = 90
    
    fmt.Println("Input:", toBitString(n, 8))
    
    result := swapsOddAndEvenBits(n)
    
    fmt.Println("Result:", toBitString(result, 8))
}



/*
run:
 
Input: 01011010
oddBits: 00001010
evenBits: 01010000
oddBits Right-shift: 00000101
evenBits Left-shift: 10100000
Result: 10100101
 
*/

 



answered Oct 26, 2025 by avibootz
...