1

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));
6
  • In the C# example, have you tried using long instead of Int64? Commented Jan 25, 2018 at 22:15
  • 2
    I guess that buffer is byte[]? Take care that in Java bytes are signed Commented Jan 25, 2018 at 22:15
  • 1
    @DFord Int64 is long. Int64 is the actual struct name and long is just an alias. Commented Jan 25, 2018 at 22:15
  • @Aominè i know they are the same and should compile the same, but based on the code, that is the first think I thought to try. Commented Jan 25, 2018 at 22:19
  • The startIndex is 26. However, without knowing what is in buffer this code cannot be run. Could you provide the values for buffer[startIndex], buffer[startIndex + 3], and buffer[startIndex + 2] when you get the result 3259945? Commented Jan 25, 2018 at 22:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

instead of ((buffer[startIndex] & 0xFF) & 0x7F), just (buffer[startIndex] & 0x7F) is needed because the sign bit has been cleared by 0x7F

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.