Sling Academy
Home/Golang/Formatting Numbers for Output in Binary, Hex, and Decimal in Go

Formatting Numbers for Output in Binary, Hex, and Decimal in Go

Last updated: November 24, 2024

Go offers excellent support for formatting numbers in various numerical systems like binary, hexadecimal, and decimal. This can be highly useful for applications such as network programming, cryptography, or simply processing computer-related data. In this article, we will explore how to format numbers in Go using its standard library functions.

Basic: Formatting Numbers in Decimal

In Go, you can easily format integers and floating-point numbers into strings. Let's start by simply printing numbers using the decimal system:

package main

import (
    "fmt"
)

func main() {
    var num int = 42
    fmt.Printf("Decimal: %d\n", num)
}

Output:

Decimal: 42

Basic: Formatting Numbers in Binary

Using Go’s fmt.Printf() function, you can also format an integer to its binary representation with the %b format verb.

package main

import (
    "fmt"
)

func main() {
    var num int = 42
    fmt.Printf("Binary: %b\n", num)
}

Output:

Binary: 101010

Basic: Formatting Numbers in Hexadecimal

Hexadecimal is another common format especially useful in low-level programming.

package main

import (
    "fmt"
)

func main() {
    var num int = 42
    fmt.Printf("Hexadecimal: %x\n", num)
}

Output:

Hexadecimal: 2a

Intermediate: Formatting Numbers with Width and Padding

You can control the output width and padding in Go. This is helpful for ensuring aligned outputs in various formats.

package main

import (
    "fmt"
)

func main() {
    num := 42
    fmt.Printf("Decimal with padding: %5d\n", num)     // Width of 5
    fmt.Printf("Binary with prefix: %#b\n", num)       // Adding prefix '0b'
    fmt.Printf("Hexadecimal with 0 padding: %04x\n", num) // 0 padding
}

Output:


Decimal with padding:    42
Binary with prefix: 0b101010
Hexadecimal with 0 padding: 002a

Intermediate: Formatting Floating-Point Numbers

Similarly, you can also format floating-point numbers. You can round, set decimal precision, or even represent them scientifically.

package main

import (
    "fmt"
)

func main() {
    num := 3.14159265
    fmt.Printf("Default float: %f\n", num)
    fmt.Printf("Float with precision: %.2f\n", num)
    fmt.Printf("Scientific notation: %e\n", num)
}

Output:


Default float: 3.141593
Float with precision: 3.14
Scientific notation: 3.141593e+00

Advanced: Custom Number Formatting

For more complex formatting, you might need to handle numbers as strings, manually adding prefixes, or manipulating the output further.

package main

import (
    "fmt"
    "strings"
)

func formatNumber(num int, base int) string {
    var prefix string
    var formatted string

    switch base {
    case 2:
        prefix = "0b"
        formatted = fmt.Sprintf("%b", num)
    case 16:
        prefix = "0x"
        formatted = fmt.Sprintf("%x", num)
    default: // Decimal
        prefix = ""
        formatted = fmt.Sprintf("%d", num)
    }

    return prefix + strings.ToUpper(formatted) // Returns upper case
}

func main() {
    num := 42
    fmt.Println("Custom Binary Format:", formatNumber(num, 2))
    fmt.Println("Custom Hexadecimal Format:", formatNumber(num, 16))
    fmt.Println("Custom Decimal Format:", formatNumber(num, 10))
}

Output:


Custom Binary Format: 0b101010
Custom Hexadecimal Format: 0x2A
Custom Decimal Format: 42

Each method employed offers different benefits depending on the level of detail and kind of formatting required. Whether you just need simple number outputs or more formatted ones, Go’s formatting capabilities have you covered.

Next Article: Parsing Hexadecimal and Binary Input Strings in Go

Previous Article: Working with Octal and Hexadecimal Numbers in Go

Series: Numbers and Math in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant