Skip to content

Instantly share code, notes, and snippets.

@dimitrilw
Last active July 31, 2023 22:27
Show Gist options
  • Save dimitrilw/e6e60e3319b5c50e658cfde5a3a8706b to your computer and use it in GitHub Desktop.
Save dimitrilw/e6e60e3319b5c50e658cfde5a3a8706b to your computer and use it in GitHub Desktop.
go (golang) least significant bit (lsb) / last set bit
// for use with signed numbers, like an int, *not* a uint
func lsb(n int) int { return n & (-n) }
func demo() {
for i := 0; i < 10; i++ {
fmt.Printf("i %d as bits %04b lsb %b\n", i, i, lsb(i))
}
}
/* output:
i 0 as bits 0000 lsb 0
i 1 as bits 0001 lsb 1
i 2 as bits 0010 lsb 10
i 3 as bits 0011 lsb 1
i 4 as bits 0100 lsb 100
i 5 as bits 0101 lsb 1
i 6 as bits 0110 lsb 10
i 7 as bits 0111 lsb 1
i 8 as bits 1000 lsb 1000
i 9 as bits 1001 lsb 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment