Search code examples
arraysgobinarybooleanbit

How to set bits of byte array


I'm trying to make a custom byte array using bits. It means that I want to set bits of a byte array. here is the demonstration:

bits := []int{ 0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,1 }

func ToByteArray(in []int) ([]byte,error){
    out := make([]byte,len(in)/8,len(in)/8)
    if len(in) == 0 || len(in)%8 != 0{
        return out,fmt.Errorf("input array is not dividable by 8")
    }
    for i:=0; i < len(in); i++{
        cell := i/8
        pos := i%8
        //cant assign shift to byte
        out[cell] |= in[i] << pos
    }   
    return out,nil
}

spew.Dump( ToByteArray(bits) )

I tried to assign shift to a byte but its not applicable. How can I create a byte array from array of integer of 0 and 1?


Solution

  • The result of the shift is an integer, not byte:

     out[cell] |= byte(in[i] << pos)