I need to port this Assembly instruction:
NEG eax
so I did following:
uint32_t a = 0x1234568;
a = reinterpret_cast<uint32_t>(-a);
since reinterpret_cast
does what I want, meaning interpreting bytes directly without any kind of casting/conversions.
- Do I need
reinterpret_cast
for this purpose? Does this violate strict aliasing?- If I do it wrong, what is the best way to implement it?
I'm asking this question because while the code apparently works under gcc, it doesn't work under Visual Studio (cannot convert from uint32_t to uint32_t
and unary minus operator applied to unsigned type, result still unsigned
). The errors make sense, but I'm not sure how can I do it in a different way except for computing 2's complementary using bit hacks.
reinterpret_cast
here, thestatic_cast
is sufficient.BTW: Your code really compiles to the "neg" instruction, at least on Intel platforms. ;-)
Update:
The C++ language specification says:
And since unsigned types are promoted to themselves, the unary minus can be applied to unsigned types and doesn't change them.
So it's correct to write, for example:
The
static_cast
can be used there but it is not needed. Thereinterpret_cast
cannot be used to convert integers.