• Advertisement
Sign in to follow this  

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

This topic is 4625 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
It'll take me a bit of time to fully understand that code, but for now, I have a question: In what situation would this kind of thing be necessary?

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