Binary is Base 2 each bit in binary has the decimal weighted representation
1, 2, 4, 8, 16
2^0 = 1,
2^1 = 2,
2^2 = 4
2^3 = 8
2^4 = 16
Eg to convert 9 to binary
9 divided by 16 = 0, with 9 remainder (4th bit is 0)
9 divided by 8 = 1 and 1 remainder (3rd bit is 1)
1 divided by 4 = 0 and 1 remainder (2nd bit is 0)
1 divided by 2 = 0 and 1 remainder (1st bit is 0)
1 divided by 1 = 1 and 0 remainder (0th bit is 1) = 01001
---------------------------------------------
Let Num = the number to be converted to binary
Let n = the number of bits you need (integer)
let array of bits(0..n) (integer)
Let rem = remainder (integer) = 0 (start at zero)
let res = result (of modulus division)
You can have a loop (for i = n to 0)
----------------------------------
algorithm.... not exactly basic code
FOR i = n to 0
res = Num mod 2^i *** mod is modulus
divide function in basic
rem = Num- [res * 2^i] *** compute the remainder
*** get what's left over from the divide
bit(i) = res *** store the result in the bit array.
Num = rem *** do it over again with what's left over
Next i
*** display bit result ***
For I = n to 0
Print bit(i); ** display each bit individually
next i
print
sommes said:
I am using BASCOM AVR and I would like to ask.
How to convert a decimal to 4 bit binary digit.
For example.
Convert 7 to 0111
Convert 8 to 1000
Convert 9 to 1001
Thank you very much