C 中的 shift 运算符在前面加上 1 而不是 0



这是代码:

#define u8 char
#define u32 unsigned int
typedef struct {
    //decoded instruction fields
    u8 cond; // Condition (f.ex. 1110 for always true)
    u8 instruction_code; // Is a constant since we only use branch
    u32 offset; // Offset from current PC
} dcdinst;
u8 mem[1024];
mem[0x0] = 0b11101010;
u8* instruction_addr = &mem[pc];
if (instruction_addr == NULL) {
    return false;
}
unsigned int first_part = instruction_addr[0];
// Here is the code that presents a problem:
// I try to get the upper part of the first byte
inst.cond = first_part >> 4;

first_part是以下字节:11101010。 inst.cond变得11111110,但我需要它00001110。

所以,我的实际问题是我想获取从地址instruction_addr开始的指令的前 4 位。我尝试通过使用右移运算符>>来做到这一点,但问题是它不是在字节左侧前面加上 0,而是在 1 之前。

我在 stackoverflow 上发现我首先必须将值转换为无符号的值,这就是我通过使用变量 first_part 所做的,但我仍然有同样的问题。我不明白为什么这种转变似乎"看到"我的变量是负变量,而它的类型是专门"无符号的"。

有人有想法吗?

您的u8类型使用char而不指定符号,这意味着它具有未定义的符号。默认情况下,编译器可能正在使用signed char。因此,您在运营和促销期间需要扩展标志。

改变:

#define u8 char
#define u32 unsigned int

自:

typedef unsigned char u8;
typedef unsigned int u32;

(或正确使用stdint.h类型(,并且您的存储实际上应该是无符号的。

使用 typedef s 也意味着编译器涉及此别名,它不仅仅是预处理器文本替换,消除了一类细微的错误。

最新更新