Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中的移位运算符在1之前而不是在0之前_C_Types_Binary_Bit Shift - Fatal编程技术网

C中的移位运算符在1之前而不是在0之前

C中的移位运算符在1之前而不是在0之前,c,types,binary,bit-shift,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

代码如下:

#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;
第一部分是以下字节:11101010。
inst.cond
变为11111110,但我需要它为00001110

所以,我的实际问题是,我想要得到指令的前4位,它从地址
指令\u addr
开始。我试图通过使用右移运算符
>
来实现这一点,但问题是,它不是在字节的左边预先加0,而是在字节的前面加1

我在stackoverflow上发现,我首先必须将值转换为无符号的值,这就是我使用变量
first\u part
所做的,但我仍然有同样的问题。我不明白为什么移位似乎“看到”我的变量是负数,而它的类型是明确的“无符号”


有人有想法吗?

您的
u8
类型正在使用
char
而没有指定符号,这意味着它有未定义的符号。默认情况下,您的编译器可能使用的是
有符号字符。因此,在运营和升级过程中,您需要接受签名扩展

更改:

#define u8 char
#define u32 unsigned int
致:

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


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

您的
u8
类型使用
char
而没有指定符号,这意味着它有未定义的符号。默认情况下,您的编译器可能使用的是
有符号字符。因此,在运营和升级过程中,您需要接受签名扩展

更改:

#define u8 char
#define u32 unsigned int
致:

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


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

你能把它简化为,这样人们就不必把六位代码粘在一起了?我不明白你为什么要定义u8字符而不是定义u8无符号字符,因此编译器知道关联,而不仅仅是预处理器。为什么假定
char
是无符号的
?为什么不使用
stdint.h`固定宽度类型,但使用自制类型?@OliverCharlesworth我压缩了所有内容。希望现在没问题。你能把它简化成一个,这样人们就不必把六位代码粘在一起了吗?我不明白你为什么要定义u8字符而不是定义u8无符号字符
。@WeatherVane:或者更好,
typedef unsigned char u8,因此编译器知道关联,而不仅仅是预处理器。为什么假定
char
是无符号的
?为什么不使用
stdint.h`固定宽度类型,但使用自制类型?@OliverCharlesworth我压缩了所有内容。希望现在一切正常。最好的部分用括号括起来。支持@WeatherVane:如果有标准类型可用,请不要使用自制固定宽度类型。最好的部分用括号括起来。支持@WeatherVane:如果有标准类型可用,请不要使用自制固定宽度类型。