C++: How do I cast an int to an unsigned long and not change any bits?

Viewed 38506

C++: How do I cast an int to an unsigned long and not change any bits? I want to pack and unpack values into memory. The word size is 64 bits.

This snippet illustrates the problem:

int v1 = -2; // 0xfe
unsigned long v2=(unsigned long)v1; // 0xfffe, I want 0x00fe

The simple solution is:

unsigned long v2=(unsigned int)v1; // 0x00fe

However, this code is in a template where the target type is a parameter, so I had to resort to this:

uint64 target = mem[index] & mask;
uint64 v;
if (value < 0) {
    switch (bits) {
    case 8:
        v = (uint8)value;
        break;
    case 16:
        v = (uint16)value;
        break;
    case 32:
        v = (uint32)value;
        break;
    }
} else {
    v = value;
}
v = v << lShift;
target |= v;
mem[index] = target;

Assume, for example, the type for "value" is an int (16 bits) and bits=16. The goal is to mask the bits in memory for value and replace them.

Does anyone know an easier way?

6 Answers
Related