我正在编写一个我正在撰写的项目代码。我正在尝试将两个字节的数据组合成一个小端的16位数(即00 02到十六进制的02 00或二进制的0000 0000 0000 0010到0000 0010 0000 0000)。我找到了一个算术解决方案,其中(最高有效位* 256)+最低有效位。但是,每当我尝试这样做时,输出都会得到零。任何人都可以弄清楚我在做错了什么吗?我的想法已经不多了。谢谢!
int main (int argc, char **argv){
int fd;
unsigned char *buffer = malloc(512);
struct fileSystem_info fat_12;
//Check if argv[1] exists
if(argc > 2){
printf("Error: The file does not exist. \n");
}
//Open the file
fd = open("fat_volume.dat", O_RDONLY, S_IROTH);
if (fd == -1){
printf("Error: Opening the file was unsuccessful \n");
}
//Read the file
if (read(fd,buffer,512) < 0){
printf("Error: Read was unsuccessful \n");
}
else{
printf("Read is successful \n" );
}
//Converts two 8 bit data to one 16 bit data
int converter(int mostSignificant_bit, int leastSignificant_bit){
return((mostSignificant_bit * 256) + leastSignificant_bit);
}
//Parse data
unsigned char first_byte = buffer[11]; //(raw byte that is read from a hex editor is 00)
unsigned char second_byte = buffer[12]; //(raw byte that is read from a hex editor is 02)
unsigned char test = converter( (int)second_byte, (int)first_byte);
printf("%hhu \n", first_byte);
//outputs 0
printf("%hhu \n", second_byte);
//outputs 2
printf("%hhu \n", test);
//outputs 0
}
答案 0 :(得分:6)
所有类型都是char,test
需要大于char。请参阅下面的两个^^更改。
unsigned char test = converter( (int)second_byte, (int)first_byte);
^^^^ should be int
printf("%hhu \n", first_byte);
//outputs 0
printf("%hhu \n", second_byte);
//outputs 2
printf("%hhu \n", test);
^^^ should be u
另外,将转换为:
unsigned converter(unsigned mostSignificant_bit, unsigned leastSignificant_bit);
答案 1 :(得分:2)
您可以通过移动msb并按位或使用lsb来完成此操作。
uint16_t value = (uint16_t)(msb << 8) | lsb;