2

I think you guy already heard of a code like this

   (c & (1 << i)) ? '1' : '0';

I already stored this on an array but it gives me a wrong binary. Here's the additional code

int i;
char test[8];
for(i=7 ; i>=0; i--){

    test[i] =(c &(1 << i)) ? '1' : '0';
}
int j = atoi(test);
printf("%d\n", j);

my sample was: 'I' it gave me : 100100109

3 Answers3

3

The behaviour of atoi(test); is undefined. The parameter test (once decayed to a pointer type) must point to a NUL-terminated array of char. Yours isn't.

The solution is trivial here, write

char test[9] = {0};

instead to force the inclusion of a NUL-terminator . But do note that the resulting number is of the order of 10 million; perhaps therefore too big for an int. Use a long instead to be sure, along with atol instead of atoi. If you want the string to be parsed as binary, then use strtol passing a radix of 2.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • `atoi` has no error control - should we recommend to use it? +1 anyway. – user2736738 Mar 01 '18 at 14:34
  • @coderredoc: `atoi` certainly has its purpose. Although that said, the C standard library I/O functions are so poor you pretty much end up writing your own. – Bathsheba Mar 01 '18 at 14:36
  • For validated input - it's alright I suppose. Otherwise there is `strtol` which is way more sophisticated than `ato*` functions. – user2736738 Mar 01 '18 at 14:37
0

To convert a number formatted as string in base 2 ("binary") to an actual integer, use strtoul():

const unsigned long x = strtoul("11100011", NULL, 2);
printf("x=%lu\n", x);

The final 2 there specifies the base, and 2 of course gives binary, and this prints 227.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

As already mentioned in other answers, the core problem is that you don't null terminate the string. But there's various other bad practice in this program:

A corrected program might look like this:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
  unsigned int c = 100;

  char test[8+1];

  for(size_t i=0; i<8; i++)
  {
    test[i] = c & (1u<<(8-1-i)) ? '1' : '0';
  }
  test[8] = '\0';

  int j = (int)strtol(test, NULL, 10);
  printf("%.8d\n", j);

  return 0;
}

Or if you live and breathe C language operator precedence (major nerd warning), you could be cocky and just write test[i] = c & 1u << 8-1-i ? '1' : '0';. As the operator precedence here is: -, <<, &, ?:, =.

Lundin
  • 195,001
  • 40
  • 254
  • 396