Sling Academy
Home/Golang/Exploring Binary Coded Decimal (BCD) with Go

Exploring Binary Coded Decimal (BCD) with Go

Last updated: November 24, 2024

Binary Coded Decimal (BCD) is a method of representing decimal numbers where each digit is represented by its own binary sequence. This system is often used in systems where a numeric value must be displayed, especially in electronic displays and digital clocks. This article will guide you through understanding BCD and demonstrate its implementation in the Go programming language.

Understanding Binary Coded Decimal (BCD)

In BCD, each digit of a number is represented by a fixed number of bits, usually four. For example, the decimal number 527 would be represented in BCD as:

  • 5 => 0101
  • 2 => 0010
  • 7 => 0111

Thus, 527 would be 0101 0010 0111 in BCD.

Basic BCD Implementation in Go

Let's start with a simple example in Go to convert a single digit to BCD:


package main

import (
    "fmt"
    "strconv"
)

func toBCD(digit int) string {
    if digit < 0 || digit > 9 {
        return ""
    }
    return fmt.Sprintf("%04b", digit)
}

func main() {
    fmt.Println("BCD of 5:", toBCD(5))
}

In this code snippet, the toBCD function takes an integer argument and returns its BCD representation as a string. The fmt.Sprintf("%04b", digit) converts the digit to its binary form with leading zeros to ensure it stays 4-bits.

Intermediate: Converting a Number to BCD

Next, let's enhance our solution to convert an entire number to its BCD representation:


package main

import (
    "fmt"
    "strconv"
)

func numberToBCD(number int) string {
    bcdStr := ""
    numStr := strconv.Itoa(number)
    for _, digitRune := range numStr {
        digit, _ := strconv.Atoi(string(digitRune))
        bcdStr += toBCD(digit) + " "
    }
    return bcdStr
}

func main() {
    fmt.Println("BCD of 527:", numberToBCD(527))
}

This code uses the numberToBCD function that iterates over each digit of the number, converts it to BCD using the toBCD helper, and appends it to the result string.

Advanced: BCD Arithmetic

Working with BCD can also involve arithmetic operations like BCD addition. Below, we demonstrate a function that adds two BCD numbers:


package main

import (
    "fmt"
    "strconv"
)

// Converts a BCD represented number string back to an integer.
func bcdToInt(bcdStr string) int {
    digits := ""
    for i := 0; i < len(bcdStr); i += 4 {
        part := bcdStr[i:i+4]
        num, _ := strconv.ParseInt(part, 2, 0)
        digits += strconv.Itoa(int(num))
    }
    result, _ := strconv.Atoi(digits)
    return result
}

func bcdAdd(bcd1, bcd2 string) string {
    num1 := bcdToInt(bcd1)
    num2 := bcdToInt(bcd2)
    sum := num1 + num2
    return numberToBCD(sum)
}

func main() {
    bcd1 := numberToBCD(517)
    bcd2 := numberToBCD(408)
    fmt.Println("BCD sum of 517 and 408:", bcdAdd(bcd1, bcd2))
}

In this example, the bcdToInt function reverses the BCD conversion process, allowing us to carry out arithmetic operations by converting BCD back to integers. The bcdAdd function then adds the corresponding integers and returns their BCD representation.

Conclusion

Binary Coded Decimal, while not commonly used as standard numbers in mainstream computing, remains an efficient representation for applications requiring precise digit manipulation. Go provides an expressive platform to experiment with such concepts, combining strong mathematical operations with simplicity. Using BCD, we can engage with interesting aspects of number representation and digital communications.

Next Article: Parsing and Formatting Hex Dumps Using Go

Previous Article: Converting Floating Point Numbers to Binary Representations 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