Tyler Dahle
Tyler Dahle

Reputation: 77

Char to binary conversion is all the sudden wrong?

I have the following code to convert a char array (like 'hi\n') to binary and store in an int array.

void data_to_binary(char *data){

bit_pos = 0;
int i = 0, j = 0, k = 0;
char mask = 0x80;

for(i = 0; i < sizeof(data); ++i){
    if(data[i] != '\0' && data[i] != '\n'){
        mask = 0x80;
        for(j = 0; j < 8; ++j){
            binary_data[bit_pos] = ((data[i] & mask) > 0);
            mask >>= 1;
            bit_pos++;
        }
    } 
}
}

This worked perfectly. I was getting 01101000 01101001 for hi. I changed NOTHING about this code and ran it again just recently and I am now getting 01111111 01111111.... I have no idea what is going on. While fiddling with unrelated code I did get a heap corruption error. Is that what is causing this? That it is still negatively impacting my code?

Upvotes: 1

Views: 78

Answers (1)

V-X
V-X

Reputation: 3029

  1. What do you expect the sizeof(data) to be? Wouldn't you use the strlen instead?
  2. You are using signed char for the mask. After first execution of "mask >>= 1;" you get 0xC0 instead of 0x40. Try using int or unsigned char, in order to avoid the sign to be set after the shift.

Upvotes: 2

Related Questions