Binary, decimal and computers

Recommended Posts

Since computers use binary numbers, how is it possible for them to display decimals?

For instance, the following (C code) will print out 10, and not a binary representation of 10.

int i = 10;

printf(i);

How is that done?

Share on other sites

The compiler knows that what you want to display is a human readable number so it converts the binary into that. If you were to look at the piece of memory that is i it would be:

00001010

Assuming that c uses just a single byte binary for integers, and not twos comp or something similar....

Share on other sites

It's rather easy to write a code constructing a string from a natural number, e.g.:

std::string result="";
for (; value!= 0; value /= 10) {

int last_digit = value - 10*(value/10);
switch ( last_digit ) {
case 0: result="0"+result; break;
case 1: result="1"+result; break;
...
case 9: result="9"+result; break;
default:
std::cout<<"You screwed up the digit "<<last_digit<<std::endl; abort();
}
}
if (result == "") result="0";


Share on other sites

So the printf function (or similar in other languages) converts the binary representations into strings - sort of an optical illusion.

Share on other sites

Slightly more abstract: It converts the number into a symbol (an ordered collection of digits) that can be displayed on the screen and understood by the reader - though not necessarily in the way I sketched. This is not exclusive to computers: Actually, when you write "10" on a piece of paper you are writing down a symbol for a number. Sidenote: The symbol "$\frac{100}{10}$" would be a different symbol for the same number.

Share on other sites

Outdated but worth noting

http://en.wikipedia.org/wiki/Binary-coded_decimal

there is more than one way......................

Create an account

Register a new account