尝试将“字节”信息存储到%x时发生位扩展

所以我目前需要读取一串hexASCII字符并使用它们来确定特定的操作码。 为此,我打开一个文本文件(它不是真的,但为了简单的解释,我们将其称之为)然后在行中读取。 所以,如果我得到一个像40f1这样的行…我让函数读取2个字符并将它们作为unsigned int存储到mem_byte中。 然后我将它转换为char用作数组并保留“byte”值的信息或两个hex数字的数值,这些数字是通过读取2个hex数字的ASCII字符表示获得的。

void getInstructions(FILE* read_file, int* stack_point, char** instructions, int size) { unsigned int mem_byte; int ins_idx = 0; char* ins_set = malloc(sizeof(char) * size); //Set size of the array of bytes for memory. Temporarily holds the memory of the program fscanf(read_file, "%d", stack_point); //Reading in the memory from the program file fscanf(read_file, " %2x", &mem_byte); //Initial read to clear whitespace ins_set[ins_idx] = (char) mem_byte; ins_idx++; while(fscanf(read_file, "%2x", &mem_byte) != 0) //Loops and reads 1 byte at a time until the fscanf hits the whitespace/end of the line its reading { ins_set[ins_idx] = (char) mem_byte; printf("Byte: %x\n", ins_set[ins_idx]); ins_idx++; } strcpy(*instructions, ins_set); //Copy the instruction set back to the original pointer for memory free(ins_set); return; 

}

所以我遇到的问题是,如果我打印出测试结果,我会得到

 Byte: 40 Byte: fffffff1 

这意味着代码将char扩展为4字节数据类型。 我不确定char是否持有unsigned int中的信息并将其打印出来,或者我误解了%x或类型转换的工作原理。 我想让我的char指令数组只保存2个hex数字的信息,仅此而已。

类型为charshort等的参数在传递给variadic函数(如printf时会隐式转换为int

因此,其中一个类型的负值将被符号扩展,以便它保持int类型的相同值; -1作为char (通常为0xFF作为unsigned char )将作为int隐式转换为-1 (它似乎在您的系统上保存0xFFFFFFFF的底层表示)。

考虑将您的参数转换为unsigned char以减轻您注意到的符号扩展。

例如printf("Byte: %x\n", (unsigned char) ins_set[ins_idx]);