-3

I'm wondering what is the best way to convert a byte to an array of bools representing the number in binary.

This would be the input:

var number byte = 170
// Equivalent binary would be: 10101010

The output would be a bool array representing the binary equivalent of the number

binary := []bool{true, false, true, false, true, false, true, false}

My plan is to then iterate over this array.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
JJ Pell
  • 846
  • 1
  • 8
  • 17

2 Answers2

2

You can just iterate the bits. Note that to get your expected output, you have to do it in reverse, as your expected output has the first element of the array representing the most significant bit of the byte.

var out [8]bool
for i := 7; i > 0; i-- {
    if in&(1<<i) > 0 {
        out[i] = true
    }
}

Working example: https://play.golang.org/p/v8NhlRvn-O6

Adrian
  • 42,911
  • 6
  • 107
  • 99
0

A basic algorithm to convert an integer number to its binary representation is to repeatedly test if the integer is even or odd (corresponding to a 0/"false" digit, or 1/"true", respectively), and dividing the number by 2 (using integer division, i.e., shifting the binary representation to the right by one position), until the number is 0.

This gives the individual bits from right to left, if you want the resulting slice to contain the bits from left to right, you need to prepend each bit to the result (see How to prepend int to slice):

func toBits (number byte) []bool {
    result := []bool{}
    for number > 0 {
        result = append([]bool{number % 2 == 1}, result...)
        number >>= 1
    }
    return result
}

Prepending to a slice repeatedly leads to multiple copy operations and reallocations. A more efficient solution would preallocate a slice with the target size and fill it from right to left. This would require either to calculate the size from the number (using a logarithm), or to just specify the size.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Note that this will result in several allocations, when you know how many to expect, and will not guarantee a len 8 slice. Leading zeroes will be omitted entirely - e.g., `0b00001111` will result in `[]bool{true, true, true, true}`. – Adrian Apr 14 '21 at 13:22