Sign in to follow this  
PurpleAmethyst

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

Recommended Posts

PurpleAmethyst    335
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
Zahlman    1682
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
Absolution    180
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this