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 s_val
, but is treated as unsigned?
This may be really simple, but after looking on Stackoverflow and elsewhere I haven't turned up the answer.
By default, numerical values in C are signed, which means they can be both negative and positive. Unsigned values on the other hand, don't allow negative numbers.
The term "unsigned" in computer programming indicates a variable that can hold only positive numbers. The term "signed" in computer code indicates that a variable can hold negative and positive values. The property can be applied to most of the numeric data types including int, char, short and long.
To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.
Variables such as integers can be represent in two ways, i.e., signed and unsigned. Signed numbers use sign flag or can be distinguish between negative values and positive values. Whereas unsigned numbers stored only positive numbers but not negative numbers.
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
.
Note that you don't need the cast at all. For all the wrangling about whether the cast will munge bits or not for negative representations, one thing has gotten lost - the cast is completely unnecessary.
Because of the conversions that C/C++ will do (and how casting is defined), this:
int64_t s_val = SOME_SIGNED_VALUE; uint64_t u_val = s_val;
is exactly equivalent to:
int64_t s_val = SOME_SIGNED_VALUE; uint64_t u_val = static_cast<uint64_t>(s_val);
That said, you might still want the cast because it signals intent. However, I've heard it argued that you shouldn't use unnecessary casts because it can silence the compiler in situations where you might want a warning.
Pick your poison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With