Macaraune Salad
Macaraune Salad

Reputation: 23

How do I store a converted char to binary number

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

Upvotes: 2

Views: 108

Answers (3)

Lundin
Lundin

Reputation: 214300

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: -, <<, &, ?:, =.

Upvotes: 0

unwind
unwind

Reputation: 399949

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.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234785

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.

Upvotes: 3

Related Questions