不能将负数在c中向右移动 [英] can't shift negative numbers to the right in c

查看:49
本文介绍了不能将负数在c中向右移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习"K& R的C语言".现在,我正在按位进行操作.我很难理解以下代码.

I am going through 'The C language by K&R'. Right now I am doing the bitwise section. I am having a hard time in understanding the following code.

int mask = ~0 >> n;

我正在使用它掩盖另一个二进制文件的n左侧.0000 11111010 0101//随机数

I was playing on using this to mask n left side of another binary like this. 0000 1111 1010 0101 // random number

我的问题是,当我打印var mask时,它仍为负-1.假设n为4,我认为将〜0(即-1)移位为15(0000 1111).

My problem is that when I print var mask it still negative -1. Assuming n is 4. I thought shifting ~0 which is -1 will be 15 (0000 1111).

感谢您的回答

推荐答案

对负值执行右移会产生一个定义的实现值.如您所见,大多数托管的实现将向左移 1 位,但是不一定必须如此.

Performing a right shift on a negative value yields an implementation defined value. Most hosted implementations will shift in 1 bits on the left, as you've seen in your case, however that doesn't necessarily have to be the case.

无符号类型以及带符号类型的正值在向右移动时总是向左移动 0 位.因此,您可以通过使用无符号值来获得所需的行为:

Unsigned types as well as positive values of signed types always shift in 0 bits on the left when shifting right. So you can get the desired behavior by using unsigned values:

unsigned int mask = ~0u >> n;

此行为记录在 C标准:

5 E1 >> E2 的结果是 E 1个右移 E2 位的位置.如果 E1 具有未签名的类型,或者 E1 具有已签名的类型和非负数值,结果的值是商的整数部分 E1/2 E2 的值.如果 E1 具有带符号的类型和负值,则结果值是实现定义的.

5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. 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 / 2E2 .If E1 has a signed type and a negative value, the resulting value is implementation-defined.

这篇关于不能将负数在c中向右移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆