C: Decimal to Binary
by admin on Oct.23, 2011, under Programming
Example of how to convert a decimal number into a binary number. The result of the function will be stored and returned in form of a char array (char*). This function will only convert a single character (byte) into its binary representation.
char* decimal_to_binary(int input) { static char buf[9]; buf[8] = '\0'; int i = -1; int j = -1; for (j=128,i=0; j>0; j>>=1,i++) { buf[i] = ( ((input & j) == j) ? 49 : 48); } return buf; }
Here’s a full example which demonstrates how to implement this method:
#include <stdio.h> char* decimal_to_binary(int input) { static char buf[9]; buf[0] = '\0'; int i = -1; int j = -1; for (j=128,i=0; j>0; j>>=1,i++) { buf[i] = ( ((input & j) == j) ? 49 : 48); } return buf; } int main(void) { printf("08d : %s \n", decimal_to_binary(255)); printf("16d : %s \n", decimal_to_binary(16)); }