Skip to content

Instantly share code, notes, and snippets.

@eienf
Last active October 29, 2023 08:58
Show Gist options
  • Save eienf/5577452 to your computer and use it in GitHub Desktop.
Save eienf/5577452 to your computer and use it in GitHub Desktop.
from binary string to decimal integer.
#include <stdio.h>
#include <stdlib.h>
unsigned long bin2dec(const char *binary)
{
unsigned long decimal = 0;
do {
if ( *binary == '0' ) {
decimal <<= 1;
} else if ( *binary == '1' ) {
decimal <<= 1;
decimal += 1;
} else if ( *binary == ' ' ) {
;
} else {
break;
}
} while ( *(++binary) != 0 );
return decimal;
}
int main(int argc,char *argv[])
{
if ( argc < 2 ) {
fprintf(stderr,"Usage:%s binnumber\n",argv[0]);
return 1;
}
// unsigned long dec = strtoul(argv[1],NULL,2);
unsigned long dec = bin2dec(argv[1]);
printf("%ld\n",dec);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment