c# - Performing bitwise left shifts on "signed" data in Java -- better to move to JNI? -
i've been asking questions on hex , bitwise manipulation (here , elsewhere) past week trying wrap head around representation in java. after googling , chagrin must ask 1 final time how perform logical arithmetic on bits ought unsigned, represented signed in java.
okay: porting c# program java. program deals bitmap manipulation, , such of data in app represented byte
, unsigned 8-bit integer. there many suggestions instead use short
data type in java in order "mimic" close possible unsigned 8-byte integer.
i don't believe that's possible me c# code performing various many shifting , and operations byte data. example, if data
byte array, , 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 simple matter of casting data
short
, being done work in java. far logic concerned requirement data stay in 8-bit unsigned significant; 16-bit unsigned screw math above up. right here? indeed, after having "fake casting" byte
0xff
, char
in java , not getting right results, afraid hit dead end.
now, in part of code, performing bitmap pixel manipulation. since it's long running process, decided make call native code through jni. realized in there use uint8_t
data type , closest representation c# byte
data type.
is solution make data-dependent functionality operate in jni? seems highly inefficient, both rewrote , perform. solution redo math in java logic remains same? seems right, has potential induce aneurysm, not mention faulty math.
i appreciate , suggestions.
just note: cannot cast directly short
, because negative numbers logically extended.
that is, byte 1111 1101
(-5) when directly cast short
result in 1111 1111 1111 1101
(-5), not 0000 0000 1111 1101
(253). must remove leading ones , operation when cast:
short shortvalue = ((short)(bytevalue)) & 0xff;
i know complex bit manipulation possible, because have done exact thing in handling legacy binary messaging protocol java swing application. highly recommend somehow abstracting away have deal once. whether means wrapping "bytes" in class store them shorts , handle conversion operations, or defining static utility conversion , bit operation in 1 pass, store bytes.
Comments
Post a Comment