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 [ ]:
# Для использования макроса @printf, нужен модуль Printf
import Pkg; Pkg.add("Printf")

# Подключение модуля Printf, который обеспечивает printf-подобный вывод
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)
    # Выводим число и его двоичное представление в формате "%6i → %s"
    @printf("%6i%s\n", n, string(n, base=2))  # base=2 означает, что мы хотим получить двоичное представление
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 [ ]:
# Те же самые числа, но теперь они выводятся с дополнением до 20 знаков в двоичном виде
for n in (0, 5, 50, 9000)
    # Используется функция string(..., pad=N), где N — минимальное количество символов
    @printf("%6i%s\n", n, string(n, base=2, pad=20))  # pad=20 гарантирует длину строки не менее 20 символов
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