Skip to content

Instantly share code, notes, and snippets.

@samueltcsantos
Created May 3, 2017 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samueltcsantos/e68b8e047d493ec7d105201101597f51 to your computer and use it in GitHub Desktop.
Save samueltcsantos/e68b8e047d493ec7d105201101597f51 to your computer and use it in GitHub Desktop.
Convert Binary to Decimal
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/**
* @desc Algorithm to convert binary to decimal number.
*
* Compile: gcc binary-to-decimal.c -o toDecimal -lm
* Run: ./toDecimal 10100101
*
* @author Samuel T. C. Santos
*/
int main(int argc, char **argv){
char* bits = argv[1];
int i=0, j=0;
//total of bits is equal to string length.
int n = strlen(bits);
int decimal = 0;
j = n;
for(i=0; i < n; i++){
int bit = (int) bits[i] - 48;
int term = bit * pow(2, --j);
decimal += term;
if(bit == 1) printf(" %d * 2 ^ %d = %d \n", bit, j,term);
}
printf("Binary: %s \n", bits);
printf("Decimal: %d \n", decimal);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment