Golang | How can I convert from int to binary?

Golang | Converting from int to binary: Here, we are going to learn how can I convert from int to binary in Go programming language?
Submitted by IncludeHelp, on August 04, 2021

Converting from int to binary in Golang

There are two ways to convert from int to binary,

1) Int to binary conversion using fmt.Sprintf()

In Golang (other languages also), binary is an integral literal, we can convert binary to int by representing the int in binary (as string representation) using fmt.Sprintf() and %b.

Golang code for int to binary conversion using fmt.Sprintf()

// Golang program for int to binary conversion
// using fmt.Sprintf()

package main

import (
	"fmt"
)

func main() {
	int_value := 123

	bin_value := fmt.Sprintf("%b", int_value)
	fmt.Printf("Binary value of %d is = %s\n", int_value, bin_value)

	int_value = 65535

	bin_value = fmt.Sprintf("%b", int_value)
	fmt.Printf("Binary value of %d is = %s\n", int_value, bin_value)
}

Output:

Binary value of 123 is = 1111011
Binary value of 65535 is = 1111111111111111

2) Int to binary conversion using strconv.FormatInt()

To convert from int to binary, we can also use strconv.FormatInt() method which is defined in strconv package.

Golang code for Int to binary conversion using strconv.FormatInt()

// Golang program for int to binary conversion
// using strconv.FormatInt()

package main

import (
	"fmt"
	"strconv"
)

func main() {
	int_value := 123

	bin_value := strconv.FormatInt(int64(int_value), 2)
	fmt.Printf("Binary value of %d is = %s\n", int_value, bin_value)

	int_value = 65535

	bin_value = strconv.FormatInt(int64(int_value), 2)
	fmt.Printf("Binary value of %d is = %s\n", int_value, bin_value)
}

Output:

Binary value of 123 is = 1111011
Binary value of 65535 is = 1111111111111111



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.