ADVERTISEMENT
ADVERTISEMENT

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

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.

Program:

// 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.

Program:

// 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

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.