Andrew Roth
Andrew Roth

Reputation: 1073

Converting code from C# to Java - Bit manipulation, Int64 to long

I'm trying to convert this snippet from C# to java. The C# snippet is correctly returning the value 3259945, the java code is incorrectly returning -16855. I'm completely useless at bit manipulation and have no idea where to even start. Can anyone help?

If people need the input variables I'll try to get the buffer byte array as a hex string so I can put it up. The startIndex I'm using is 26.

C# snippet:

Int64 mantissa = ((Int64)(buffer[startIndex] & 0x7F) << (8 * 2))
                        | ((Int64)buffer[startIndex + 3] << (8 * 1))
                        | ((Int64)buffer[startIndex + 2] << (8 * 0));

Java Snippet:

long mantissa = ((long)(buffer[startIndex] & 0x7F) << (8 * 2))
                | ((long)buffer[startIndex + 3] << (8 * 1))
                | ((long)buffer[startIndex + 2] << (8 * 0));

Upvotes: 1

Views: 274

Answers (1)

NightOwl888
NightOwl888

Reputation: 56869

As mentioned in the comments, in .NET a byte is unsigned (0 to 255) and in Java it is signed (-128 to 127). To normalize it, you need to use the & 0xFF mask.

long mantissa = ((long)(buffer[startIndex] & 0x7F) << (8 * 2))
            | ((long)(buffer[startIndex + 3] & 0xFF) << (8 * 1))
            | ((long)(buffer[startIndex + 2] & 0xFF) << (8 * 0));

In the first case, you don't need this mask because the sign bit has been cleared by 0x7F.

Upvotes: 2

Related Questions