Reputation: 11
I need to get the lowest 31 bits of some integer, that is bigger than standard 32 bit int.
Either getting an 32 bit int with the lowest 31 bits of the large integer, or getting a filled bytearray from the large integer will suffice.
In c# I would use BigInt and .toByteArray - is there something similar in c++11 (I am a noob in c++)?
Upvotes: 1
Views: 317
Reputation: 1121
Assuming you have the value in a long variable, you can get the 31 bits you want in a 4 byte array with a code like this example:
#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;
}
Of course that the order of bytes will depend on your system.
Upvotes: 0
Reputation: 98816
Mask the lowest 31 bits and return the result:
template<typename T>
T mask31(T x) {
static_assert(std::is_integral<T>::value, "mask31 is only supported on integers!");
return x & (T)0x7fffffff;
}
If you know the types you are working with, you can of course do away with the template goop and just mask directly inline :-)
Upvotes: 5