madcrazydrumma
madcrazydrumma

Reputation: 1897

Char array to binary array not working

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!

Upvotes: 0

Views: 98

Answers (2)

LSerni
LSerni

Reputation: 57408

Oopsie:

 char **string

You want to pass a string, that is a char *. You're instead passing a pointer to a pointer.

This

int stringLength = (sizeof(string) / sizeof(char)) + 1;

appears to be working by chance, because sizeof(string) returns 4 (the size of a pointer) on your platform, and "Hello" is 5 characters. You want

int stringLength = strlen(string);

This also will not work:

char charArray[stringLength * 8]; //* 8 for char bits?

because its memory only "lives" inside the function. To pass it outside, you need to allocate it using malloc():

char *charArray;
charArray = malloc(8*stringLength+1);
// Check that malloc returned a valid pointer. It's almost certain
// that it will, but the one time it might return NULL...
if (charArray == NULL) {
    // ...you want to know it. Using charArray now would crash.
    printf("An error occurred\n");

    // Either return something harmless or something that will
    // show to the upstream code that an error occurred.
    return NULL;
}

Upvotes: 3

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Your calculation of stringLength is wrong, the sizeof is an operator and it gives you the size of a type, objects having array type will of course return the size of the array. But your string variable is not an array it's a pointer, and the size of a poitner is not the length of the contents it points to.

Also, I suspect you are doing something else wrong because this

char c = string[i];

is wrong, the type of string[i] is char * not char.

You didn't post all the code, but those are 2 mistakes in your code. It's not clear why you are passing char ** to the function if you don't want to alter the parameter.

Upvotes: 4

Related Questions