我需要获得某个整数的最低31位,这比标准的32位int大。
要么使用大整数的最低31位获得32位int,要么从大整数获得填充的bytearray就足够了。
在c#中我会使用BigInt和.toByteArray - 在c ++ 11中是否有类似内容(我是c ++中的noob)?
答案 0 :(得分:5)
屏蔽最低31位并返回结果:
template<typename T>
T mask31(T x) {
static_assert(std::is_integral<T>::value, "mask31 is only supported on integers!");
return x & (T)0x7fffffff;
}
如果你知道你正在使用的类型,你当然可以取消模板goop并直接屏蔽内联: - )
答案 1 :(得分:0)
假设你有一个长变量的值,你可以在4字节数组中得到你想要的31位,代码如下例所示:
#include <stdint.h>
#include <stdio.h>
int main(){
long int lvalue = 0x1234567890abcdefL;
unsigned char byteArray[4];
*(int32_t *)byteArray = (int32_t)(lvalue & 0x7fffffffL); // 0x10abcdef
for(int i=0; i<4; i++)
printf("Byte[%d] = %02X\n", i, byteArray[i]);
return 0;
}
当然,字节顺序取决于您的系统。