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) from2through36specifying the number base (for example,2for binary,8for octal,16for hexadecimal, or36for 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 values0through9(where available in the chosen base). -
Letters
A-Z(ora-z): Represent values10through35(A/a=10,B/b=11, ...,Z/z=35). Case does not change the numeric value.
-
Mathematical Digits
We are going to write few integers using this syntax:
1> 2#1101.
13
2> 8#77.
63
3> 16#1a.
26
4>
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>
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)