[] byte到[] int或[] bool

Let's say I have a []byte and for the sake of making my life easier I want to convert it in a []int or []bool in the following way:

Let's say I start with []byte{0x41}, that is 0b01000001. Now, what I would like to obtain is something like:

[]int{0,1,0,0,0,0,0,1}

or

[]bool{f,t,f,f,f,f,f,t}

I guess I could cycle with something like this:

mybyte & (1 << pos)

but I was looking for a more compact approach.

There is no ready function in the standard lib that would do that. Here's a possible solution using a loop:

func convert(data []byte) []bool {
    res := make([]bool, len(data)*8)
    for i := range res {
        res[i] = data[i/8]&(0x80>>byte(i&0x7)) != 0
    }
    return res
}

You explained you want to convert []byte to []bool because you treat the input as a set of individual bits.

In that case just use big.Int. It has Int.Bit() and Int.SetBit() methods to get and set a bit at a given position. To "initialize" a big.Int value with the raw []byte, use Int.SetBytes(). If you modify / manipulate the big.Int, you may get back the raw bytes using Int.Bytes().

See this example:

data := []byte{0x41, 0x01}
fmt.Println("intput bytes:", data)

bi := big.NewInt(0)
bi.SetBytes(data)
fmt.Println("data:", bi.Text(2))

fmt.Println("7. bit before:", bi.Bit(7))
bi.SetBit(bi, 7, 1)
fmt.Println("7. bit after:", bi.Bit(7))
fmt.Println("data:", bi.Text(2))
fmt.Println("output bytes:", bi.Bytes())

Output (try it on the Go Playground):

intput bytes: [65 1]
data: 100000100000001
7. bit before: 0
7. bit after: 1
data: 100000110000001
output bytes: [65 129]