c - C 中的移位运算符前置一个而不是零

标签 c types binary bit-shift

代码如下:

#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 而未指定符号,这意味着它具有 undefined symbol 。您的编译器可能默认使用 signed char。因此,您需要在运营和促销期间进行签到延期。

改变:

#define u8 char
#define u32 unsigned int

到:

typedef unsigned char u8;
typedef unsigned int u32;

(或正确使用 stdint.h 类型),并且您的存储实际上应该是未签名的。

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

关于c - C 中的移位运算符前置一个而不是零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43239906/

相关文章:

c - 查找二进制数中的前导 1

c - C 编程中反转数组

c - 指针分配二维数组指针的警告消息

c - struct task_struct 成员?

haskell - 如何定义只接受数字的数据类型?

java - double a = a + int b 和 int a += double b 有什么区别?

xcode - 嵌入式二进制

c - 显示字符串中每个字符的二进制

c - 为什么 opencv 中的 FindContours 函数会找到两个轮廓而不是图像中的一个轮廓,如下所示?

haskell - Haskell 中类型的推理