How do you read every N bits?

Viewed 154

There's an 64 bit signed integer and I'm trying to read every 4 bits.

a := int64(1229782938247303441)
for i := 0; i < 16; i++ {
    fmt.Printf("%v\n", byte(a) >> 4)
    a >>=  4 
}

The last value is 0 which should be 1.

1 Answers

Use a & 0xf to get the bottom 4 bits.

The value 0xf has a one bit in the low four bits and zeros in all other bits. The result of the bitwise AND expression a & 0xf has the low four bits from a and zeros in all other bits.

a := int64(1229782938247303441)
for i := 0; i < 16; i++ {
    fmt.Printf("%v\n", a & 0xf)
    a >>=  4 
}
Related