简体   繁体   English

在C中对负数进行按位运算

[英]Bitwise operations on negative numbers in C

What is the effect of the following? 以下的作用是什么?

unsigned int x = -1; x >>= 2;

I'm not quite sure what the x gets set to as it's a negative number and the type is unsigned? 我不太确定x设置为负数,并且类型是无符号的吗?

unsigned int x = -1;

sets x to UINT_MAX (section 6.3.1.3, point 2)¹. x设置为UINT_MAX (第6.3.1.3节,第2点)¹。 The int -1 is converted to unsigned int for the initialistaion of x . 对于x的初始unsigned int ,将int -1转换为unsigned int That conversion is done by adding (or subtracting, but not here) UINT_MAX +1 to the value until it is in the range 0 .. UINT_MAX , once here. 通过将UINT_MAX +1到该值(直到在此范围之内,直到它在0 .. UINT_MAX范围内)来完成该转换。

Thus x >>= 2; 因此x >>= 2; sets x to UINT_MAX/4 , since bitwise right shift of unsigned integers is thus specified in section 6.5.7, point 5: x设置为UINT_MAX/4 ,因为在6.5.7节第5点中指定了无符号整数的按位右移:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. E1 >> E2的结果是E1右移E2位位置。 If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2 E2 . 如果E1具有无符号类型或E1具有符号类型和非负值,则结果的值是E1 / 2 E2商的整数部分。

¹ "Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type." ¹“否则,如果新类型是无符号的,则通过重复添加或减去比新类型可表示的最大值多一个值来转换值,直到该值在新类型的范围内为止。”

-1应该将unsigned int设置为0xffffffff,这是该类型的最高数字(大约48亿)-如果int的位数超过32位,则该数字应高得多。

It is an unsigned type initialised by a signed negative value. 它是由带符号负值初始化的无符号类型。 The shifting is still performed on an unsigned value. 移位仍对无符号值执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM