ofiz
ofiz

Reputation: 101

How do computers convert to binary?

I am aware of an algorithm I can write to convert a given number into binary, namely the one in which I divide by two and look at the remainder and so forth. However I am missing something crucial.

When I write in my code:

int x = 56;

The computer wants to convert 56 to binary because that is the only language it knows, but it can't divide 56 by 2 because 56 is not in binary. My question is, how does a computer do it? Does it convert each single digit to binary, multiplies by 10 and add them together or is there a faster way?

Upvotes: 0

Views: 396

Answers (2)

Patrick87
Patrick87

Reputation: 28332

The compiler uses an algorithm to convert the string of decimal digits "56" to a numeric value ultimately stored as a string of bits "00111000". "56" might be laid out like this in memory:

Address     Value    Comment
...
0xabab1212  0x35     This is the hex representation of the ASCII code for "5"
0xabab1213  0x36     This is the hex representation of the ASCII code for "6"
0xabab1214  0x00     Assuming null-terminated strings as in C
...

The representation of the numeric value would look like:

Address     Value    Comment
...
0xabab1220  0x38     The hex representation of the decimal number 56
...

The hex values 0x35, 0x36 and 0x38 are just short-hand notations for the underlying bit sequences 00110101, 00110110 and 00111000, which is what the hardware actually works in.

The key takeaway is that there is no such thing as a "number" on a computer. There are only strings - which we may use to represent numbers - and all computation is done by manipulating strings. You type in a string, the compiler generates a string, and the hardware stores a string.

Upvotes: 1

user3344003
user3344003

Reputation: 21647

The computer only works in binary. When you put

int x = 56;

in your code, this is just text. When you compile the text 56 will be converted into a binary NUMERIC value.

There is a difference between binary numeric representation and binary text. This

111000

and

56

Are text representations of the same number. If you had the former in a program (such as Ada that supports binary text) the compiler would still have to convert it to a binary numeric value.

Upvotes: 0

Related Questions