So I'm trying to make a string to binary method in C. Here is my code so far:
int main(int argc, char **argv) {
convertStringToBits("hello");
}
char *convertStringToBits(char **string) {
int i;
int stringLength = strlen(string);
int mask = 0x80; /* 10000000 */
char charArray[stringLength * 8]; //* 8 for char bits?
for(i = 0; i < (sizeof(string) / sizeof(char)) + 1; i++) {
mask = 0x80;
char c = string[i];
while(mask > 0) {
printf("%d", (c & mask) > 0);
mask >>= 1; /* move the bit down */
//add to char array
}
printf("\n");
}
return charArray;
}
The expected output of: hello should be:
01101000
01100101
01101100
01101100
01101111
But i get this:
01101000
01101111
01100011
00100000
01011011
I also want to return an array of characters but I can't seem to do this.
Thanks for the help!
sizeof(char)is always 1.CHAR_BITSis 8 or not, that's something else butsizeof(char)MUST be 1.int stringLength = (sizeof(string) / sizeof(char)) + 1;- this will not work as expected