convert decimal value to binary

Status
Not open for further replies.
Do you know a formula that could easily convert decimal value to binary, hexadecimal, octal value?
 
Last edited by a moderator:
Binary to Hex and Octal is a piece of cake.

convert: 111 101 b to octal would be 75 7*8+5 = 61 decimal
Convert 0011 1101 to hex is 3C would be 3*16 + 13 = 61 decimal

Note all, I did was re-arrange the binary value in groups of 3 and 4 e.g. 0011 = 13 and 1101 = 8+4+1 = 13 and 13 is Hex C

Decimal to Binary, you just have to figure out the weights. e.g. 65536 32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
I have the power of 2 table memorized.
So 32+16 = 48+8 = 56 add 4 = 60 add 1 = 61 and we find that 32 is set, 16 is set, 8 is set, 4 is set, 2 isn't set and 1 is set.
so you get 111101 binary

Which is what I started with.

Formulas get wierd because it depends on the representation. For positive numbers a shift right is a divide by 2 and a shift left 1 bit is multiply by 2. When they are two's complement it gets even stranger. When you can use the shift and and operators in C, it's not too bad.
One trick in programming is to say print chr$(48+n) where n=0-9 and it will print a "0" to a "9"
Some Basics have a mid$() function, so MID$("0123456789ABCDEF",n+1,1) could give you a digit from 0 to F as an ASCII character.

The number 61 .AND. 15 = 13 and the 13'th character is a "C"
The integer of (61/16) = 3 .AND. 15 = 3; the third character is a "3" (the /16 is shift right 4 binary places)
So you get "3C"

Now, if I said convert -1 to binary, hex and octal it's gonna be a lot harder. You need representation (2's complement usually) and number of bits.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…