Last active
October 29, 2023 08:58
-
-
Save eienf/5577452 to your computer and use it in GitHub Desktop.
from binary string to decimal integer.
This file contains hidden or 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> | |
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