Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Converter decimal to binary using the little endian format.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define BIT_0 "0"
#define BIT_1 "1"
/**
* @desc Convert a decimal number to binary using the Little-Endian format.
*
* Compile: * gcc -o binary-little-endian.c -o toBinary
* Run: ./toBinary 100
*
* @author Samuel T. C. Santos
*/
/**
* Reverse in place a sequence of bits that represent a binary number.
*/
void reverseBits(char str[]){
int len = strlen(str);
char tmp, i, j;
int middle = len / 2;
for(i=0, j=len-1; i < j; i++, j--){
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
}
int main(int argc , char **argv){
int number = atoi(argv[1]);
char bits[64] = "";
char r=0;
int q=1;
while (q > 0){
q = number / 2;
r = number % 2;
(r == 0) ? strcat(bits, BIT_0) : strcat(bits, BIT_1);
printf("n = %d , q = %d, r = %d \n", number, q, r);
number = q;
}
printf("Big-Endian %s \n", bits);
reverseBits(bits);
printf("Little-Endian %s \n", bits);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment