gpt4 book ai didi

c - 尝试将 "byte"信息存储到 %x 时发生位扩展

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:29 25 4
gpt4 key购买 nike

所以我目前需要读入一串十六进制 ASCII 字符,并使用它们来确定特定的操作码。为此,我打开一个文本文件(它不是真的,但为了简单的解释,我们称之为)然后读入该行。因此,如果我得到像 40f1 这样的行......我让函数读取 2 个字符并将它们作为无符号整数存储到 mem_byte 中。然后我将它转换成一个 char 以用作数组并保留“字节”值的信息或两个十六进制数字的数值,这些数字是通过读取 2 个十六进制数字的 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 个十六进制数字的信息,仅此而已。

最佳答案

charshort 等类型的参数在传递给诸如 的可变参数函数时会隐式转换为 int printf.

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

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

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

关于c - 尝试将 "byte"信息存储到 %x 时发生位扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45665673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com