Decimal to binary using simple coding in c language? | Sololearn: Learn to code for FREE!
0

Decimal to binary using simple coding in c language?

29th Dec 2021, 1:13 AM
Hariharanvignesh K
3 Answers
29th Dec 2021, 1:36 AM
CGM
CGM - avatar
+ 2
I'm no expert but the way I did it was to use bitwise '&' with a 1 to get the value (state) of the least significant bit of the number, then start filling an int array, then, just continue (using some sort of loop) whilst doing a right shift until the number is 0, then output the array in reverse order. (only works for a positive integer though) One thing I don't like about my method was the fact that it's in an int array, What I might try (tomorrow) is to fill a char array using a switch/case construct , reverse it then append a null '\0' and output it as a string.
29th Dec 2021, 1:41 AM
rodwynnejones
rodwynnejones - avatar
0
Here is a slightly less mathy way, by using a lookup table. Reformat the decimal number into a hexadecimal or octal string by using sprintf. (Too bad, sprintf won't format directly to binary). Then, digit by digit, from a lookup table print the binary bit pattern that defines that digit. Here is an implementation that uses octal, which conveniently has only 8 digits to look up: https://code.sololearn.com/c1WcNAGuZrrg/?ref=app
29th Dec 2021, 12:05 PM
Brian
Brian - avatar