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)
CodePudding user response:
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("b\n", myvar) // prints 00001111
CodePudding user response:
func ConvertToByte(bits [8]bool) byte {
var b byte
for _, bit := range bits {
b <<= 1
if bit {
b |= 1
}
}
return b
}