Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[]byte to []int or []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.

like image 703
mgm Avatar asked Feb 27 '18 10:02

mgm


People also ask

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes().

What is byte array?

The bytearray() method returns a bytearray object, which is an array of bytes. It returns a mutable series of integers between 0 and 256. The source parameter of the ByteArray is used to initialize the array.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


1 Answers

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]
like image 78
icza Avatar answered Nov 21 '22 22:11

icza