Created
May 3, 2017 02:08
-
-
Save samueltcsantos/e68b8e047d493ec7d105201101597f51 to your computer and use it in GitHub Desktop.
Convert Binary to Decimal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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