【发布时间】:2015-08-15 23:34:33
【问题描述】:
我想知道是否有一种方法可以像在 Python 中的 C/C++ 中那样使用标准库(最好在位数组上)进行二进制补码扩展。
C/C++:
// Example program
#include <iostream>
#include <string>
int main()
{
int x = 0xFF;
x <<= (32 - 8);
x >>= (32 - 8);
std::cout << x;
return 0;
}
这是我编写的一个 Python 函数,它(在我的测试中)完成了同样的事情。我只是想知道是否有内置(或更快)的方法:
def sign_extend(value, bits):
highest_bit_mask = 1 << (bits - 1)
remainder = 0
for i in xrange(bits - 1):
remainder = (remainder << 1) + 1
if value & highest_bit_mask == highest_bit_mask:
value = (value & remainder) - highest_bit_mask
else:
value = value & remainder
return value
【问题讨论】:
-
啊,之前因为某种原因没看到。感谢您指出这一点。
-
这是一个字符串转换。