Search code examples
gobit-manipulationbytebitwise-operatorsbit

golang: How to get first bit of byte


I have a hash:

b := hash.Sum(nil)

I am really just interested in the first bit of that byte. Is it 0 or 1?

So far I have this:

s := strconv.FormatInt(int64(b[0]),2)
if s[0] == '0' {
 // it's 0
} else {
  // it's 1
}

But I am sure there is a much more elegant (and more performant?) way to do this.


Solution

  • you could just check the result of bitwise and operator

    if b[0] & 0x1 == 0x1 {
        // it's 1
    } else {
        // it's 0
    }