Jump to content
  • Advertisement
Sign in to follow this  
PurpleAmethyst

[java] Storing two 16 bit values (short) in one int

This topic is 4807 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

I was going to ask this as a question but the solution came into my head while I was typing the post, so just in case anyone else is interested, here is how to store two signed short in one int: short x = 21; short y = -67; int pos = (int)(y << 16) + ((int)x&0xFFFF); System.out.println( "X is " + (short)(pos & 0xFFFF) ); System.out.println( "Y is " + (pos>>16)); Hope someone else finds this useful!

Share this post


Link to post
Share on other sites
Advertisement
Note that the (short) cast is quite necessary here: otherwise, the bit-masking returns an int-sized value with the high bits all clear, which will therefore not be sign-extended. In effect, it transforms the low short into an "unsigned short".

This behaviour (by omitting the cast) is quite useful in certain contexts :)

Share this post


Link to post
Share on other sites
I used this kind of thing in a couple of areas when I was writing a software renderer. It was very useful and necessary for packing color data into a single pixel. This kind of bit shifting and masking was also useful in the inner loop of my renderer where I used some fixed point math to avoid casting. Fortunately, in those two applications I could use unsigned data.

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!