How to convert binary string to int number in C

3 Answers

0 votes
#include <stdio.h>
#include <inttypes.h>
  
int main() 
{ 
	char s[] = "1001"; 
  
	int n = strtoimax(s, NULL, 2);
    
	printf("%d\n", n);
	
    return 0; 
}



/*
run:

9

*/

 



answered Oct 15, 2019 by avibootz
0 votes
#include <stdio.h>
   
int strbin2int(char *s) {
  char *p = s;
  unsigned int i = 0;

  while (p && *p) {
    i <<= 1;
    i += (unsigned int)((*p++) & 0x01);
  }

  return (int)i;
}
   
int main() 
{ 
    char s[] = "1001"; 
   
    int n = strbin2int(s);
     
    printf("%d\n", n);
     
    return 0; 
}
 
 
 
/*
run:
 
9
 
*/

 



answered Jul 15, 2020 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
   
int main() 
{ 
    char s[] = "1001"; 

	int base = 2, n;
    char *endptr;

    n = strtol(s, &endptr, base);
     
    printf("%d\n", n);
     
    return 0; 
}
 
 
 
/*
run:
 
9
 
*/

 



answered Jul 15, 2020 by avibootz

Related questions

2 answers 161 views
161 views asked Nov 25, 2023 by avibootz
4 answers 348 views
1 answer 132 views
2 answers 480 views
480 views asked Oct 18, 2014 by avibootz
1 answer 276 views
276 views asked Oct 17, 2014 by avibootz
2 answers 287 views
1 answer 150 views
150 views asked Jul 31, 2022 by avibootz
...