C++ 中 MSB ->LSB 和 LSB->MSB 的有符号 INT 转换
我检查了 SWAR 算法(SIMD Within A Rregister)用于反转 无符号整数
。 signed int
有类似的东西吗?
I checked out the SWAR algorithm (SIMD Within A Register) for reversing bit order of unsigned int
s. Is there something similar for signed int
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该算法仅适用于无符号整数,因为在位移期间不需要符号扩展。
由于该算法仅使用二进制表示形式,而不是数值,因此您可以将其转换为相同大小的无符号整数(它将具有相同的表示形式),使用该算法,然后转换回有符号整数。这些转换不会变成任何汇编指令,它们只会导致编译器产生逻辑右移而不是算术右移。
The algorithm only works on unsigned integers, since sign-extension during bit-shifting is not wanted.
Since the algorithm uses only the binary representation, not the numeric value, you can just cast to an unsigned integer of equal size (it will have identical representation), use the algorithm, and cast back to signed. These conversions won't turn into any assembly instructions, they just cause the compiler to produce logical shift right instead of arithmetic shift right.
这取决于反转有符号整数的位的含义。然而,一般来说,如果您计划将符号位放在 LSB 位置,并将 LSB 放在符号位中(这是交换任何内容的正常方法),那么相同的算法可以用于有符号和无符号整数。
如果不是这种情况,请解释一下反转有符号整数的含义。
It depends on what you mean by reversing the bits of a signed integer. However, in general, if you plan to place the sign bit in the LSB position and the LSB in the sign bit (which is the normal way to swap anything) then the same algoritm could be used for both signed and unsigned integers.
If this isn't the case, please explain what you mean by reversing a signed integer.