您可以控制​​按位右移将用C填? [英] Can you control what a bitwise right shift will fill in C?

查看:161
本文介绍了您可以控制​​按位右移将用C填?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我知道,当你用C使用左移位运算符它保证了空缺位将被填充0。不过,我读过的右移是实现相关,在某些机器空置位将被以0填充,在其他人,他们将用1填充的意思。

As far as I know when you use a left shift bitwise operator in C it's guaranteed that the vacant bits will be filled with 0s. However, I've read that the right shift is implementation-dependent, meaning in some machines the vacant bits will be filled with 0s, in others they will be filled with 1s.

我正在使用的程序的右移,而事实上我的机器是用ls填补空缺位。问题是,我需要它来填补,而不是0

I am using the right shift in a program, and indeed my machine is filling the vacant bits with 1s. Problem is I would need it to fill with 0s instead.

有没有办法强制0要在右移使用吗?

Is there a way to force 0s to be used on right shifts?

一个解决办法是,在应用右移后,营造出宛如011111111面具,然后应用按位与,这将改变被插入到最左边的1 0。

One solution would be, after the right shift is applied, to create a mask like 011111111 and then apply a bitwise AND, which will change the leftmost 1 that was inserted to a 0.

但是,这是麻烦,浪费时间。如果有一种方式来告诉我的机器,以填补1S右移那就容易多了。

But this is cumbersome and wastes time. If there was a way to tell my machine to fill right shifts with 1s it would be much easier.

感谢

推荐答案

投数无符号,然后转移。这将迫使0填充。

Cast the number to unsigned and then shift. That will force a 0-fill.

这篇关于您可以控制​​按位右移将用C填?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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