C 中负整数的逻辑右移?
在 C 语言中如何对负数进行逻辑右移?基本上我正在寻找 Java 中 >>>
的 C 等效项,
即
int one = -16711936 ;
//int two = -16711936 ;
//int three = -1;
int r, g, b;
System.out.println(Integer.toBinaryString(one));
r = one << 8;
r >>>= 24;
g = one << 16;
g >>>= 24; //this always ends up being -1 in C, instead of 255
b = one << 24;
b >>>= 24;
How does one go about doing a logical right shift of negative numbers in C? Basically I am looking for the C equivalent of >>>
in java
i.e.
int one = -16711936 ;
//int two = -16711936 ;
//int three = -1;
int r, g, b;
System.out.println(Integer.toBinaryString(one));
r = one << 8;
r >>>= 24;
g = one << 16;
g >>>= 24; //this always ends up being -1 in C, instead of 255
b = one << 24;
b >>>= 24;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与 Java 不同,C 有无符号整数类型。您应该始终使用无符号整数类型进行像这样的按位操作。除非您是 C 语言专家,否则使用带符号类型将导致您进入未定义行为的可怕领域,恶魔会从您的鼻子里飞出来。
Unlike Java, C has unsigned integer types. You should always use unsigned integer types for bitwise manipulation like this. Unless you're an expert in C, doing it with signed types is going to lead you into the scary realm of undefined behavior where demons fly out of your nose.
在移位之前将值转换为
(unsigned int)
。Cast the value to
(unsigned int)
before shifting.