[英]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: 我一直在尝试将二进制数转换为char,我使用以下代码将char转换为二进制:
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" 例如,如果我转换字符串“ hola”,则第一个代码显示为“ 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: 编辑1:
One problem is that you are copying too many bytes into subbuff
with 一个问题是您将太多字节复制到
subbuff
,
memcpy( subbuff, &fichero[k], k+8 );
Another is that you pass a bad pointer to memcpy
with 另一个是您通过传递了一个错误的
memcpy
指针
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! 最终,您的位序列被颠倒了,因此您将不会获得原来的
char
!
EDIT 2: after adding a few lines to the above code and reversing the bits in the hola
definition, I get this output. 编辑2:在上述代码中添加几行并反转
hola
定义中的位后,得到此输出。 Obviously you must make sure that result[]
is long enough. 显然,您必须确保
result[]
足够长。
Program output: 程序输出:
01101000 = h = 104 = 0x68
01101111 = o = 111 = 0x6F
01101100 = l = 108 = 0x6C
01100001 = a = 97 = 0x61
Result = hola
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.