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.
>>and&in*temp >> bit_index & 1? Does the compiler know? Are you both in agreement? I strongly recommend the use of parentheses, for the benefit of those who come after even if you know the answer straight off. Separately, maybe you should show the output you get and the output you want. It may make it easier for people to help you.strncat()that it is OK to write up tosizeof(final)characters after the end of whatever string is already stored infinal. The interface tostrncat()is even worse than the interface tostrncpy(); it is very difficult to get the code correct, and you have to know how long the string in the target is before you can say how much space there is left, which really makes it pointless (you could usememmove()ormemcpy()orstrcpy()or perhapsstrncpy()instead). I'd forget thatstrncpy()exists -- I only work with it on Stack Overflow when people ask.