Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to binary in Go

Tags:

string

binary

go

How do you convert a string to its binary representation in Go?

Example:

Input: "A"

Output: "01000001"

In my testing, fmt.Sprintf("%b", 75) only works on integers.

like image 721
deepwell Avatar asked Jul 10 '26 21:07

deepwell


1 Answers

Cast the 1-character string to a byte in order to get its numerical representation.

s := "A"
st := fmt.Sprintf("%08b", byte(s[0]))
fmt.Println(st)

Output:  "01000001"

(Bear in mind code "%b" (without number in between) causes leading zeros in output to be dropped.)

like image 126
SnoProblem Avatar answered Jul 13 '26 16:07

SnoProblem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!