How to copy bits from M into N (numbers) between bit positions i and j (edge‑case‑safe) in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

/*
    Handles edge cases:
    - Validates i and j
    - Prevents undefined behavior from shifting by ≥ 64 bits
    - Masks M so only the required bits are copied
*/

// Convert unsigned 64‑bit integer to binary string without leading zeros
func toBinary(x uint64) string {
    if x == 0 {
        return "0"
    }

    s := ""
    for x > 0 {
        if x&1 == 1 {
            s = "1" + s
        } else {
            s = "0" + s
        }
        x >>= 1
    }
    return s
}

// Copy bits from M into N between bit positions [i, j]
func copyBits(N, M uint64, i, j int) uint64 {
    if i < 0 || j < 0 || i > j || j >= 63 {
        panic("Invalid bit range")
    }

    length := j - i + 1

    // Mask for bits i..j
    mask := ((uint64(1) << length) - 1) << i

    // Clear bits i..j in N
    Ncleared := N &^ mask

    // Take only the needed bits from M and shift into place
    Mshifted := (M & ((uint64(1) << length) - 1)) << i

    return Ncleared | Mshifted
}

func main() {

    /*
        N:      100 011111 00
        M:          110011
        Result: 100 110011 00
    */

    N := uint64(0b10001111100)
    M := uint64(0b110011)

    result := copyBits(N, M, 2, 7)

    fmt.Println("N:      ", toBinary(N))
    fmt.Println("M:      ", toBinary(M))
    fmt.Println("Result: ", toBinary(result))
}



/*
OUTPUT:

N:       10001111100
M:       110011
Result:  10011001100

*/

 



answered Mar 30 by avibootz

Related questions

...