Is there a built-in function to convert a uint
to a slice of binary integers {0,1}
?
>> convert_to_binary(2)
[1, 0]
Is there a built-in function to convert a uint
to a slice of binary integers {0,1}
?
>> convert_to_binary(2)
[1, 0]
I am not aware of such a function, however you can use strconv.FormatUint
for that purpose.
Example (on play):
func Bits(i uint64) []byte {
bits := []byte{}
for _, b := range strconv.FormatUint(i, 2) {
bits = append(bits, byte(b - rune('0')))
}
return bits
}
FormatUint
will return the string representation of the given uint
to a base, in this case 2, so we're encoding it in binary. So the returned string for i=2
looks like this: "10"
. In bytes this is [49 48]
as 1 is 49 and 0 is 48 in ASCII and Unicode. So we just need to iterate over the string, subtracting 48 from each rune (unicode character) and converting it to a byte.