how to convert string to binary in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert string to binary in golang, just use fmt.Sprintf() method with "%s%b" argument, it will convert string into binary.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows/


Today, I will show you how do I convert string to binary in golang, as above mentioned I’m going to use fmt.Sprintf() way.

The fmt package provide fmt.Sprintf() method.

Let’s start our Golang convert string to binary example

Convert whole string into binary example

main.go

package main
import "fmt"

func strToBin(s string) (binString string) {
    for _, c := range s {
        binString = fmt.Sprintf("%s%b",binString, c)
    }
    return 
}

func main() {
  s := "aguidehub"
  res := strToBin(s)
	fmt.Printf(res)
}

In the above example, we have converted string to binary and printed in golang console. let’s check the output.

Output

110000111001111110101110100111001001100101110100011101011100010

Try it Yourself

I hope it helps you, All the best 👍.

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts