简体   繁体   中英

How to convert an array of characters to binary array in C language

I know that this question seems familiar with this Conversion of Char to Binary in C , but is not exactly the same. I am converting an array of characters to binary integers. As a second step I am trying to concatenate them in an array of integers. I am converting the integers back to characters so I can concatenate them. The script seems to be working fine, but for some reason that I can not understand when I print the whole string it produces a not printable character at the beginning of the string.

Sample of code:

#include <stdio.h>
#include <string.h>

int main(void) {

  char *temp;
  char str[2];
  char final[32];

  for (temp = "LOCL"; *temp; ++temp) {
    int bit_index;
    for (bit_index = sizeof(*temp)*8-1; bit_index >= 0; --bit_index) {
      int bit = *temp >> bit_index & 1;
      printf("%d ", bit);

      snprintf(str, 2, "%d", bit);
      printf("This is test: %s\n",str);
      strncat(final , str , sizeof(final) );
    }
    printf("\n");
  }
  printf("This is the array int: %s\n",final);

  return 0;
}

Can someone help me understand where I am going wrong?

Thanks in advance for the time and effort to assist me.

You just forgot to initialise final , so you're concatenating your binary string onto whatever garbage happens to be in final when you run the code. You also need to allow for one extra char in final (to hold the '\\0' terminator). Change:

char final[32];

to:

char final[33] = "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM