0

I need to parse a network packet which consists of two bytes: first one consists of 8 bits that set certain flags depending on their order (for instance) and the second one is uint8 (which is simple)

  • 1 - online
  • 0 - not active
  • 1 - isPretty
  • 1 - isHandsome
  • 0 - bald
  • 0 - deaf
  • 0 - mute
  • 0 - blind

How do I parse it from a byte primitive?

Slx.x
  • 57
  • 1
  • 7
  • 2
    There's no automatic way to "parse" bits from a byte, but it sounds like what you're looking for is a simple bitmask: https://yourbasic.org/golang/bitmask-flag-set-clear/ – Adrian Feb 21 '19 at 14:22
  • 1
    See [Difference between some operators “|”, “^”, “&”, “&^”. Golang](https://stackoverflow.com/questions/28432398/difference-between-some-operators-golang/28433370#28433370); and [Extract bits into a int slice from byte slice](https://stackoverflow.com/questions/52811744/extract-bits-into-a-int-slice-from-byte-slice/52811969#52811969). – icza Feb 21 '19 at 14:28

1 Answers1

4

Some useful Go standard library packages for dealing with binary:

For extracting single bits from a byte, you ought to use bitwise operators - |, & and >>.

For example:

package main

import (
    "fmt"
)

func main() {
    v := byte(0xB2)
    if (v >> 4) & 1 == 1 {
        fmt.Println("bit 4 (counting from 0) is set")
    }
}

This checks bit 4 (with bit 0 being the lowest bit in the byte) by shifting the byte value 4 positions to the right and AND-ing with 1. You can check the other bits in your flag value similarly. Feel free to write a function that replaces the 4 in the sample above with an argument N to check bit number N.

You can find more examples in other SO answers like this one or the ones @icza linked to in a comment.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 2
    Does probably not matter in this example, but `v & (1<<4) != 0` would be a bit more efficient because the shift can then be done at compile time. – Henry Feb 21 '19 at 14:48