Performing bitwise left shifts on “signed” data in Java — better to move to JNI?

I've been asking questions on hex and bitwise manipulation (here and elsewhere) for the past week trying to wrap my head around their representation in Java. After much Googling and chagrin I must ask one final time how to perform logical arithmetic on bits that ought to be unsigned, but are represented as signed in Java.

Okay: I am porting a C# program to Java. The program deals with bitmap manipulation, and as such much of the data in the app is represented as byte, an unsigned 8-bit integer. There are many suggestions to instead use the short data type in Java in order to "mimic" as close as possible the unsigned 8-byte integer.

I don't believe that's possible for me as the C# code is performing various many shifting and AND operations with my byte data. For example, if data is a byte array, and this block of code exists in C#:

int cmdtype = data[pos] >> 5;
int len = (data[pos] & 0x1F) + 1;

if (cmdtype == 7)
{
    cmdtype = (data[pos] & 0x1C) >> 2;
    len = ((data[pos] & 3) << 8) + data[pos + 1] + 1;
    pos++;
}

It's not a simple matter of just casting data as a short and being done with it to get it to work in Java. As far as the logic is concerned the requirement that my data stay in 8-bit unsigned is significant; 16-bit unsigned would screw math like the above up. Am I right here? Indeed, after having previously "fake casting" byte with 0XFF and char in Java and not getting the right results, I am afraid I hit a dead end.

Now, in another part of the code, I am performing some bitmap pixel manipulation. Since it's a long running process, I decided to make a call to native code through JNI. I realized recently that in there I could use the uint8_t data type and get the closest representation to the C# byte data type.

Is the solution to make all my data-dependent functionality operate in JNI? That seems highly inefficient, both to rewrote and to perform. Is the solution to redo the math in Java so the logic remains the same? That seems right, but has the potential to induce an aneurysm, not to mention faulty math.

I appreciate any and all suggestions.

5
задан gjtorikian 16 November 2010 в 21:43
поделиться