2016-11-23 36 views
1

我需要得到某個整數的最低31位,即大於標準32位整數。C++中任意大小的整數的最低31位11

獲得大整數中最低31位的32位整數或從大整數中獲取填充字節數組就足夠了。在c#中我會使用BigInt和.toByteArray - 有什麼類似的c + + 11(我是一個noob在c + +)?

回答

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做掉,只是掩蓋直接內嵌:-)

0

假設你有在長變量的值,可以用這樣的例子的代碼獲得想要的31位以4字節數組:

#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; 
} 

當然是b的順序ytes將取決於你的系統。