Engee documentation
Notebook

Converting numbers to binary notation

This example demonstrates how the Julia programming language can convert decimal numbers to binary and format the output.

Introduction

The algorithm for working with binary numbers described below allows you to convert numbers from decimal to binary. This is a fundamental process in computer science, since most calculations at the hardware level take place precisely on binary representations of data. The binary representation is convenient for analyzing the bit structure of numbers, bitwise operations, and understanding the basics of computer computing.

The main part

In [ ]:
# To use the @printf macro, you need the Printf module.
import Pkg; Pkg.add("Printf")

# Connecting the Printf module, which provides printf-like output
using Printf
   Resolving package versions...
   Installed UnicodePlots ─ v3.8.1
  No Changes to `~/.project/Project.toml`
  No Changes to `~/.project/Manifest.toml`

Simple conversion of numbers to binary without padding

We iterate over the numbers 0, 5, 50 and 9000

In [ ]:
for n in (0, 5, 50, 9000)
    # We output the number and its binary representation in the format "%6i → %s"
    @printf("%6i%s\n", n, string(n, base=2))  # base=2 means that we want to get a binary representation.
end
     0 → 0
     5 → 101
    50 → 110010
  9000 → 10001100101000

Conversion with the addition of leading zeros (padding)

The argument used here is pad to ensure the minimum width of the string, filling it with zeros on the left.

In [ ]:
# The same numbers, but now they are output with a complement of up to 20 characters in binary form.
for n in (0, 5, 50, 9000)
    # The string(..., pad=N) function is used, where N is the minimum number of characters.
    @printf("%6i%s\n", n, string(n, base=2, pad=20))  # pad=20 guarantees a string length of at least 20 characters
end
     0 → 00000000000000000000
     5 → 00000000000000000101
    50 → 00000000000000110010
  9000 → 00000010001100101000

Conclusion

We have considered a simple way to convert integers from decimal to binary using the built-in function string() and formatted output via @printf. We also learned how to specify the minimum string length using the parameter pad, filling in the missing characters with zeros. This approach can be useful when working with data that requires bitwise structure analysis or when implementing logic related to binary masks. Such knowledge will be especially relevant when studying programming of microcontrollers, network protocols or working with low-level data.

The example was developed using materials from Rosetta Code