Main page Problems Volumes Ranking Mess Wiki Help News

Number to Digits

Studying the internal representation of the numbers inside the computers is important in several aspects. Programming of the data storages and the data transfer channels requires strong understanding of how the numbers are built from bytes. On the other hand the number theory deals with many properties of the number representation directly and is employed in the fields of cryptography and other kinds of data encoding.

For the first approximation we can assume that the numbers are stored in the computer memory as a single intact variable. Such aspect is very useful when we need to have numbers represented as a sequence of digits. For example, when printing them in human-readable format.

Though most programming languages have built-in functions to convert numbers into string representation, it is quite important to know how it is performed (and to be able to write algorithms based on similar idea).

Common approach

Suppose, we have a number stored in a variable and we want to find out, by which digits it should be represented, for example in decimal numeral system. - divide the number by 10, keeping the remainder; - remainder of division is the last digit of the number; - result of division should be divided by 10 again; - remainder of the second division is the second last digit; - and so on, until the result of sequential divisions becomes 0.

Let us see an example:

1492 div 10 = 149 and 2 as a remainder
149 div 10 = 14 and 9 as a remainder
14 div 10 = 1 and 4 as a remainder
1 div 10 = 0 and 1 as a remainder

Now we know that 1492 consists of digits 1, 4, 9, 2 - the fact looks bit stupid and naive - but just because we, unlike computers, use numbers already represented as their decimal notation.

Other numeral systems

But see, the same algorithm could be used to get representation of the number in numeral system with base other than 10. For example, let us find how 1492 looks in octal numeral system:

1492 div 8 = 186 and 4 as a remainder
186 div 8 = 23 and 2 as a remainder
23 div 8 = 2 and 7 as a remainder
2 div 8 = 0 and 2 as a remainder

So 1492 in octal is 2724.

If we will try to represent the same number as hexadecimal, we will see a funny thing:

1492 div 16 = 93 and 4 as a remainder
93 div 16 = 5 and 13 as a remainder
5 div 16 = 0 and 5 as a remainder

Surprise is that we have no digit to represent 13. In computer science latin letters used to represent digits greater than 9, i.e. the sequence of digits looks like:

0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N ...

From this row we take as many digits as is necessary for given numeral system (up to F for hexadecimal). So 1492 will be represented as 5D4 in hexadecimal.