Skip to content

Instantly share code, notes, and snippets.

@onema
Last active August 29, 2015 14:20
Show Gist options
  • Save onema/82cfb0b55db454fed34f to your computer and use it in GitHub Desktop.
Save onema/82cfb0b55db454fed34f to your computer and use it in GitHub Desktop.
Bit insertion
// bit_manipulation.go
// You are given two 32-bit numbers, `N` and `M`, and two bit positions,
// `i` and `j`. Write a method to set all bits between `i` and `j` in `N`
// equal to `M` (e.g. , `M` becomes substring of `N` located at i and string at `j`).
//
// EXAMPLE:
// input: N = 10000000000, M, 10101, i = 2, j = 6
// Output: N = 100001010100
package main
import (
"fmt"
)
func main() {
bitInsert(35, 10, 3, 2)
}
func bitInsert(N uint32, M uint32, i uint32, j uint32) {
difference := j - i
fmt.Printf("N:%b, M:%b, i:%d, j:%d\n", N, M, i, j)
x := M << j
x = x >> difference
fmt.Printf("new M:%b\n", x)
result := N | x
fmt.Printf("result:%b\n", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment