DEV Community

Novatus
Novatus

Posted on

Writing some tough numbers

Assumptions:

  • You had read previous article on numbers in Erlang.

Now as you know what Erlang integers are and how they are written as well as how they correspond to mathematical integers, we will go forward from here.

I hope you are familiar with Positional numeral systems (place value & radix) in mathematics. If not then revise that chapter from your school's maths textbooks.

Let's now write our integers in custom radix. To do that in Erlang we have a simple syntax base#digits.

How the Two Parts Work ?

  • base: A mathematical integer (in decimal number system) from 2 through 36 specifying the number base (for example, 2 for binary, 8 for octal, 16 for hexadecimal, or 36 for base-36). Outside this range (1, 37, negative numbers, or non-integers), it gets rejected.

  • digits: One or more characters representing the value in that base. The characters are as follows:

    • Mathematical Digits 0-9: Represent values 0 through 9 (where available in the chosen base).
    • Letters A-Z (or a-z): Represent values 10 through 35 (A/a = 10, B/b = 11, ..., Z/z = 35). Case does not change the numeric value.

We are going to write few integers using this syntax:

1> 2#1101. 
13 
2> 8#77. 
63 
3> 16#1a. 
26 
4>
Enter fullscreen mode Exit fullscreen mode

You can also put a leading - or + before base#digits.

Below it the table of results plus some extras.

Erlang Integers Base Digits Used Decimal Value
2#1101 2 (binary) 0, 1 13
8#77 8 (octal) 0-7 63
16#1a 16 (hex) 0-9, a-f 26
16#1A 16 (hex) 0-9, A-F 26 (same as 16#1a)
36#Z 36 (base-36) 0-9, A-Z 35
36#10 36 (base-36) 0-9, A-Z 36
-16#FF 16 (hex, negative) 0-9, A-F -255

What if base goes outside the range ?

4> 1#12. 
#12. 
* 1:1: illegal base '1' 
4> 45#98678. 
#98678. 
* 1:1: illegal base '45' 
4>
Enter fullscreen mode Exit fullscreen mode

Erlang rejects it.

As seen above the base#digits syntax is quite useful. The base#digits syntax lets you write integers directly in non-decimal bases such as 2, 8, 16, etc.

Top comments (0)