Reputation: 824
How does a computer turn binary, say, 110011 (51), to the corresponding ASCII values, 53('5') and 49('1')? Furthermore, how does a computer turn 53 and 49 back to 110011?
Upvotes: 2
Views: 2691
Reputation: 3733
Binary to decimal conversion normally works as a repeated division loop. If we start with a number N, (N mod 10) is the final digit and then we proceed by dividing N by 10 and repeating to get the other digits.
Converting from a string to the internal representation is even easier.
In the next iteration (i.e. for "1"=ASCII 49) Subtract 48 again: 49-48=1. We add 1 to the accumulator giving 51. No more characters so we are done and the result is 51.
The fact that the computer's internal representation is binary is incidental. We only need to be able to add, subtract and multiply to convert a string to a number inside the computer.
(Of course subtraction is just addition of a negative number and multiplication is just a sequence of additions, so addition is all that's really needed.)
Upvotes: 4
Reputation: 2847
To turn binary into ASCII:
1) take your number divide it by 10 decimal (1010 binary) and calculate the remainder 2) With the remainder, add 48 (the ASCII value for '0'). This gives you the last digit. 3) If the quotient is 0, stop 4) If the quotient is more than 0, start again from step 1 using the quotient.
Eg. Convert 51 (110011) to ASCII using base 10 (1010):
110011 / 1010 = 0101 (5 decimal) remainder 0001
0001 (the remainder from above) + 110000 ('0') = 110001 (49 decimal or '1' in ASCII)
0101 (the quotient from above) / 1010 = 0 remainder 0101
0101 (the remainder) + 110000 ('0') = 110101 (53 decimal or '5' in ASCII)
Upvotes: 0
Reputation: 13946
It doesn't turn them either way. The 53
is always a 53
in memory.
What happens is that when it needs to be displayed, a function gets called that knows that when it sees the number 53
, it generates the graphics our eyes see as a 5
. Or within memory it may turn the number 53
into the numbers 53
and 51
, which ultimately some program will display as the characters "5"
and "3"
.
And the 53
is always 110101
. A memory cell is a sequence of bits and holds decimal 53
as the bits 001101011
.
Again, there are functions that see those bits and can generate on your screen the character "5"
and the character "3"
.
But inside the computer its always numbers and its always binary.
Upvotes: 0
Reputation: 100040
Try to write a computer program for this purpose. It's generally done in software, though some processors have special purpose decimal instructions. Just pretend that it's your job to look at slips of paper with binary integers on them and produce slips of paper with Unicode code points on them, and you'll have the basic outline in no time.
Upvotes: 0