bbg bbg -4 years ago 117
C++ Question

interpret signed as unsigned

I have a value like this:

int64_t s_val = SOME_SIGNED_VALUE;

How can I get a

uint64_t u_val

that has exactly the same bit pattern as
, but is treated as unsigned?

This may be really simple, but after looking on Stackoverflow and elsewhere I haven't turned up the answer.

Answer Source
int64_t s_val = SOME_SIGNED_VALUE;
uint64_t u_val = static_cast<uint64_t>(s_val);

C++ Standard 4.7/2 states that:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ]

From the other hand, Standard says that "The mapping performed by reinterpret_cast is implementation-defined. [Note: it might, or might not, produce a representation different from the original value. ]" (5.2.10/3). So, I'd recommend to use static_cast.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download