Converting Between Denary and Binary

There are two problems here, converting from denary (base 10) to binary (base 2) and from binary to denary.

Denary to Binary

The algorithm for converting a denary number to binary is:

For example: 19 in 8 bits:

19 mod 2 = 1 - store in string array
19 div 2 = 9

9 mod 2 = 1 - store in string array
9 div 2 = 4

4 mod 2 = 0 - store in string array
4 div 2 = 2

2 mod 2 = 0 - store in string array
2 div 2 = 1

1 mod 2 = 1 - store in string array
1 div 2 = 0

0 mod 2 = 0 - store in string array
0 div 2 = 0

0 mod 2 = 0 - store in string array
0 div 2 = 0

0 mod 2 = 0 - store in string array
0 div 2 = 0

Reverse the bits collected: 00010011 = 16 + 2 + 1 = 19

An additional issue is converting between the edit boxes on a typical Delphi form and the numerical format required for calculations. There are various ways to do this. One would be to convert the bits from the mod operation into characters and store them in a string. Another is to store the integers that result from the mod operation in an array of integers.

Code

Binary to Denary

In this case we need to move along a string of bits and, if the bit is a '1', add the appropriate value to the total (a power of 2):

For the number of bits required (e.g. 1 to 8) do
Read the next bit in the binary string
 if the bit is a '1' then do
  begin
   if the loop index is 1 then add 128
   if the loop index is 2 then add 64, etc.
  end loop
output the answer

Code

The first text box is called 'denary_text', the second 'binary_text'.

Back