Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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