How to convert int to binary with leading zeros in Go

1 Answer

0 votes
package main

import "fmt"

// IntToBinary converts an integer to its binary string representation
// padded with leading zeros to match the specified bit width.
func IntToBinary(num int, bits int) string {
	// %0*b is a format specifier where:
	// - '0' specifies zero-padding
	// - '*' dynamically takes the width argument (bits)
	// - 'b' formats the integer in binary (base 2)
	return fmt.Sprintf("%0*b", bits, num)
}

func main() {
	// Define the data provided
	num := 153

	// 1. Convert to an 8-bit binary representation (153 fits within 8 bits: 0 to 255)
	binStr8 := IntToBinary(num, 8)

	// 2. Convert to a 16-bit binary representation to demonstrate wider padding
	binStr16 := IntToBinary(num, 16)

	// Display the results
	fmt.Printf("Original Integer: %d\n", num)
	fmt.Printf("Binary (8-bit)  : %s\n", binStr8)
	fmt.Printf("Binary (16-bit) : %s\n", binStr16)
}


/*
run:

Original Integer: 153
Binary (8-bit)  : 10011001
Binary (16-bit) : 0000000010011001

*/

 



answered 10 hours ago by avibootz
...