Convert binary format string to int, in C

How to convert a binary string like "010011101" to int and how to convert an int, for example 5, to a string "101" in C?

+7
c
source share
6 answers

If this is a homework problem, you probably want to implement strtol , you will have a loop like this:

 char* start = &binaryCharArray[0]; int total = 0; while (*start) { total *= 2; if (*start++ == '1') total += 1; } 

If you want a fantasy, you can use them in a loop:

  total <<= 1; if (*start++ == '1') total^=1; 
+10
source share

The strtol function in the standard library takes a "base" parameter, which in this case will be 2.

 int fromBinary(const char *s) { return (int) strtol(s, NULL, 2); } 

(the first C code I wrote after about 8 years :-)

+19
source share

I think it really depends on some questions about your lines / programs. If, for example, you knew that your number would not exceed 255 (IE you used only 8 bits or 8 0s / 1s), you could create a function in which you pass it 8 bits from your string, move it and add to the amount you returned every time you press 1. IE, if you press the bit at 2 ^ 7, add 128, and the next bit that you typed is 2 ^ 4, add 16.

This is my quick and dirty idea. I think more and google for being at school .: D

0
source share

For the second part of the question, that is, "how to convert an int, for example 5, to the string" 101 "in C?", Try something like:

 void ltostr( unsigned long x, char * s, size_t n ) { assert( s ); assert( n > 0 ); memset( s, 0, n ); int pos = n - 2; while( x && (pos >= 0) ) { s[ pos-- ] = (x & 0x1) ? '1' : '0'; // Check LSb of x x >>= 1; } } 
0
source share

You can use the following encoding

 #include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { int nRC = 0; int nCurVal = 1; int sum = 0; char inputArray[9]; memset(inputArray,0,9); scanf("%s", inputArray); // now walk the array: int nPos = strlen(inputArray)-1; while(nPos >= 0) { if( inputArray[nPos] == '1') { sum += nCurVal; } --nPos; nCurVal *= 2; } printf( "%s converted to decimal is %d\n", inputArray, sum); return nRC; } 
0
source share

Use this:

 char c[20]; int s=23; itoa(s,c,2); puts(c); 

Output:

 10111 
0
source share

All Articles