Jump to content
  • Advertisement
Sign in to follow this  
Kest

Casting bitflags

This topic is 3666 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!