Casting bitflags

Started by
2 comments, last by Kest 15 years, 8 months ago
In C/C++, what is the appropriate method to cast from signed int to unsigned int (or vice versa) in order to preserve all of the bit values? I don't need to preserve the interpreted integer value, just the exact binary bit values. Do you just use a normal static cast? Or does a static cast flip the sign bit in some situations?
Advertisement
As far as I'm aware, there is no standard conforming and well defined way to guarantee an exact bitwise copy. In practice, just assigning the value as usual works. The only problem comes when the signed values is negative, which doesn't fit into the unsigned value, but the bit pattern of the wrap-arounded value turns out to be exactly the same in 2's complement. So just assign as usual, with an explcit static_cast if you have to deal with warning.
Quote:Original post by Kest
In C/C++, what is the appropriate method to cast from signed int to unsigned int (or vice versa) in order to preserve all of the bit values? I don't need to preserve the interpreted integer value, just the exact binary bit values.
This might be what you're looking for:
signed int i = ...;unsigned int ui = *(reinterpret_cast<unsigned int*>(&i));
I don't do this sort of casting much in C++, so I may be wrong about it being the correct or optimal solution to this problem. (Also, perhaps you could tell us why you need to perform this cast, as it may be that there are other, better solutions available.)
Thanks for the quick responses.

I was considering reinterpret_cast to be the best bet, but I wasn't sure if it was overkill.

Quote:Original post by jyk
Also, perhaps you could tell us why you need to perform this cast, as it may be that there are other, better solutions available.

My scripting engine doesn't make use of unsigned integer parameters, and I need to pass a set of bitflags to the engine through it. The engine code receiving the value is aware of all of this, and must cast it to avoid a warning.

This topic is closed to new replies.

Advertisement