This should be simple but I’m having trouble changing some C code that uses bitwise operators and shifts into Java.
In C I have:
unsigned short Color(byte r, byte g, byte b)
{
return( ((unsigned short)g & 0x1F )<<10 | ((unsigned short)b & 0x1F)<<5 | (unsigned short)r & 0x1F);
}
This function, Color, returns 16bits where 15 of them represent three 5bit values for red, green, and blue color channels. I’m trying to do something similar in Java except I’m having trouble with data types.
In java I have:
int r=someval, g=anotherval, b=yetanotherval;
And I want to convert these integers to a 2byte data type and use the same bitwise/shift operations as above.
What is the best way to approach this? I was thinking of a 2byte array but that seems unnecessary.
edit
So I gave it a try in Java with shorts but there still seems to be an issue. I started simple with:
short r=someval, g=anotherval, b=yetanotherval;
short colorData = g & 0x001F;
But the compiler complains: “cannot convert from int to short”
You have the
shorttype in Java as well, but it’s always signed, there is no unsigned in Java.Therefore, it might be better to use an
int, so you don’t need to use the sign bit to hold actual color data, which can be a bit (no pun intended!) confusing.This should work as a starting point, at least:
I made the arguments
intas well, for simplicity’s sake.Update: It sounds (and seems) as if you can actually use
short, since you only need 15 bits for the color format. Then let’s do that:I haven’t tried compiling the above, but it’s likely that you’ll get conversion errors and will need to add explicit
shortcasts throughout to make it compile.