BAR
BAR

Reputation: 17111

Golang - convert [8]bool to byte

I am trying to convert a bool array of length 8 into a byte. Anyone know how?

mei := [8]bool{true, true, true, true, false, false, false, false}
myvar := ConvertToByte(mei)

Upvotes: 2

Views: 2183

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74267

Just a little bit-twiddling. Iterate over the array:

func boolsToByte( flags [8]bool ) (b byte) {
    mask := byte(0x80)
    for _, f := range flags {
        if f {
            b |= mask
        }
        mask >>= 1
    }
    return b
}

Upvotes: -1

malificent
malificent

Reputation: 36

Iterate through the bits, shifting and setting as you go.

Here's the code for the case where the most significant bit is at index 0 in the array:

func ConvertToUint8(mei [8]bool) uint8 {
    var result uint8
    for _, b := range mei {
        result <<= 1
        if b {
            result |= 1
        }
    }
    return result
}


mei := [8]bool{true, true, true, true, false, false, false, false}
myvar := ConvertToUint8(mei)
fmt.Printf("%b\n", myvar) // prints 11110000

Here's the code for the case where the least significant bit is at index 0 in the array:

func ConvertToUint8(mei [8]bool) uint8 {
    var result uint8
    for _, b := range mei {
        result >>= 1
        if b {
            result |= 0b10000000
        }
    }
    return result
}

mei := [8]bool{true, true, true, true, false, false, false, false}
myvar := ConvertToUint8(mei)
fmt.Printf("%08b\n", myvar) // prints 00001111

Upvotes: 2

Hymns For Disco
Hymns For Disco

Reputation: 8395

func ConvertToByte(bits [8]bool) byte {
    var b byte
    for _, bit := range bits {
        b <<= 1
        if bit {
            b |= 1
        }
    }
    return b
}

Upvotes: 2

Related Questions