Standard library support
fmt.Printf("%b", r)
- this solution is already very compact and easy to write and understand. If you need the result as a string
, you can use the analog Sprintf()
function:
s := fmt.Sprintf("%b", r)
You can also use the strconv.FormatInt()
function which takes a number of type int64
(so you first have to convert your rune
) and a base where you can pass 2
to get the result in binary representation:
s := strconv.FormatInt(int64(r), 2)
Note that in Go rune
is just an alias for int32
, the 2 types are one and the same (just you may refer to it by 2 names).
Doing it manually ("Simple but Naive"):
If you'd want to do it "manually", there is a much simpler solution than your original. You can test the lowest bit with r & 0x01 == 0
and shift all bits with r >>= 1
. Just "loop" over all bits and append either "1"
or "0"
depending on the bit:
Note this is just for demonstration, it is nowhere near optimal regarding performance (generates "redundant" string
s):
func RuneToBin(r rune) (s string) {
if r == 0 {
return "0"
}
for digits := []string{"0", "1"}; r > 0; r >>= 1 {
s = digits[r&1] + s
}
return
}
Note: negative numbers are not handled by the function. If you also want to handle negative numbers, you can first check it and proceed with the positive value of it and start the return value with a minus '-'
sign. This also applies the other manual solution below.
Manual Performance-wise solution:
For a fast solution we shouldn't append strings. Since strings in Go are just byte slices encoded using UTF-8, appending a digit is just appending the byte value of the rune '0'
or '1'
which is just one byte (not multi). So we can allocate a big enough buffer/array (rune
is 32 bits so max 32 binary digits), and fill it backwards so we won't even have to reverse it at the end. And return the used part of the array converted to string
at the end. Note that I don't even call the built-in append
function to append the binary digits, I just set the respective element of the array in which I build the result:
func RuneToBinFast(r rune) string {
if r == 0 {
return "0"
}
b, i := [32]byte{}, 31
for ; r > 0; r, i = r>>1, i-1 {
if r&1 == 0 {
b[i] = '0'
} else {
b[i] = '1'
}
}
return string(b[i+1:])
}