简体   繁体   中英

Binary to char converting in c

I have been trying to convert a binary number into a char, I use the following code to convert the char into binary:

void bin(char x){
    int y;
    for(y = 0; y < sizeof(char) * 8; y++){
    fprintf(f2,"%c", ( x & (1 << y) ) ? '1' : '0' );
}}

And it works fine.

The problem is that I don't know how to undo it, I want to get this binary number and convert it to the initial char. I'm using the folliwing code but it generates a core problem.

char subbuff[9];
memcpy( subbuff, &fichero[0], 8 );
subbuff[8] = '\0';


for(int k=8;k<fichero_len;k+=8){        

    char c = strtol(subbuff, 0, 2);
    printf("%s = %c = %d = 0x%.2X\n", subbuff, c, c, c);
    memcpy( subbuff, &fichero[k], k+8 );
    subbuff[8] = '\0';  

}

for exaple if i convert the string "hola" the first code shows "00010110111101100011011010000110"

but if i put that into the second code:

const char *hola="00010110111101100011011010000110";
char subbuff[16];
memcpy( subbuff, hola[0], 8 );
subbuff[8] = '\0';


for(int k=8;k<strlen(hola);k+=8){   
    char c = strtol(subbuff, 0, 2);
    printf("%s = %c = %d = 0x%.2X\n", subbuff, c, c, c);
    memcpy( subbuff, &hola[k], k+8 );
    subbuff[8] = '\0';  

}

it generates a core problem

EDIT 1:

One problem is that you are copying too many bytes into subbuff with

memcpy( subbuff, &fichero[k], k+8 );

Another is that you pass a bad pointer to memcpy with

memcpy( subbuff, hola[0], 8 );

which will cause a segfault. Please enable compiler warnings.

There is no need even to do that first, outside of the loop. It can be done similar like this

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

int main(void) {
    const char *hola = "01101000011011110110110001100001";
    char subbuff[9];
    char result [256] = "";
    unsigned char c;
    int k;
    int index = 0;
    int fichero_len = (int)strlen(hola);

    for(k = 0; k < fichero_len; k += 8) {    
        memcpy(subbuff, &hola[k], 8);                   // <--- copy 8 butes only
        subbuff[8] = '\0';  
        c = (unsigned char)strtol(subbuff, 0, 2);
        printf("%s = %c = %d = 0x%.2X\n", subbuff, c, c, c);
        result[index++] = c;
        result[index] = '\0';
    }
    printf("Result = %s\n", result);
    return 0;
}

Finally your bit sequences are reversed, so you won't get the char back that you started with!

EDIT 2: after adding a few lines to the above code and reversing the bits in the hola definition, I get this output. Obviously you must make sure that result[] is long enough.

Program output:

01101000 = h = 104 = 0x68
01101111 = o = 111 = 0x6F
01101100 = l = 108 = 0x6C
01100001 = a = 97 = 0x61
Result = hola

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