如果我正确地移动,我是否必须将最重要的位设置为零?
假设我有一个64位的数字和一些设置的值,可以说三个位。我有一个面具来获得该价值。要获得这三个位的值,我用面具的数字来获得数字。这将所有其他位设置为零。然后,我需要向右转向最低的显着位,因此三位数中最小显着的位位于64位数字中最小的位。向右移动后,我是否需要再次掩盖以确保这三位左侧的所有位均为零?
Let's say I have a 64-bit number and some bits that are set that hold a value, let's say three bits. I have a mask to get that value. To get the value of those three bits I bitwise 'AND' the number with the mask. This sets all other bits to zero. I then need to shift right towards the least significant bits so the least significant bit of the three-bit number is in the position of the least significant bit of the 64 bit number. After I shift right, do I need to mask again to ensure only all the bits to the left of those three bits are zero?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以先进行换档,然后再掩盖并完成您想要的东西:
You can do shift first then the mask and accomplish what you want:
在C ++标准的先前版本中,负值的右移是定义的,因为签名的整数可能是一个组合,两个组合或符号+幅度。因此,定义了负面转移的正确转移行为。
但是(现代)C ++的所有实现均用于CPU使用两个组合,并且许多现有代码都依赖于该实现细节。在C ++ 2020中,这终于得到认可,并且签名的整数现在被定义为两个组合。
右转的方式工作方式取决于参数的类型:
假设两个符合现在需要的两个组合,这将使用算术移动并保留符号位。因此,在偏移之后,值仍将为-1,并设置所有位。如果您在轮班前掩盖,则在班次之后您会得到更多的位,然后您会讨价还价。
这将使用逻辑偏移并在左侧添加零。因此,如果您在轮班前掩盖,则在班次之后您仍然可以获得正确的位。
但是,为什么在轮班前掩饰呢?如果轮班后掩盖,则无论类型如何,您总是会得到正确的位。
In prior versions of the C++ standard, right-shifts of negative values were implementation-defined because signed integers could be one's-complement, two's-complement or sign+magnitude. So the behavior of right shift of a negative was implementation defined.
But all implementations of (modern) C++ are for CPUs using two's-complement and a lot of existing code relies on that implementation detail. In C++ 2020 this was finally acknowledged and signed integers are now defined as two's-complement.
The way shift right works depends on the type of the argument:
Assuming two's-complement, which is now required, this will use an arithmetic shift and preserves the sign bit. So after the shift the value will still be -1 and have all bits set. If you mask before the shift then after the shift you get more bits then you bargained for.
This will use a logical shift and add zeroes to the left. So if you mask before the shift then you still get the right bits after the shift.
But why mask before the shift? If you mask after the shift then you always get the right bits regardless of the type.
是的,如果掩码的结果是签名类型,则需要一个掩码来应对位点移动。
不,如果掩码的结果是未签名类型。
如果代码确实:
智能编译器可能会像上面的 unsigned 方法一样高效。
Yes, if the result of the mask was a signed type, a mask needed to cope with the sign bit shifted.
No if the result of the mask was a unsigned type.
If code did:
A smart compiler may emit efficient as as the unsigned approach above.