Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting java method to C#: converting bytes to integers with bit shift operators

I am trying to convert the following 2 methods into c# without the .net compiler complaining at me. Quite frankly I just don't understand how the two methods are really working behind the scenes. So an answer and explanation would be great here.

public static int bytesToInt(byte b0, byte b1, byte b2, byte b3)
{
        return (((int)b0 << 24) & 0xFF000000)
            | (((int)b1 << 16) & 0x00FF0000)
            | (((int)b2 << 8) & 0x0000FF00)
            | ((int)b3 & 0x000000FF);
}

public static byte[] charToBytes(char c)
{
    byte[] result = new byte[2];

    result[0] = (byte) ((c >>> 8) & 0x00FF);
    result[1] = (byte) ((c >>> 0) & 0x00FF);

    return result;
}

The second method is particularly confusing because of the shift operator being used that is different that the first method.

Thanks in advance for any help.

like image 402
TheDevOpsGuru Avatar asked Aug 03 '11 02:08

TheDevOpsGuru


People also ask

Can Java be converted to C?

Yes, there's a Java to C source converter: a human programmer. (Reliability may be an issue, though.) If you really want to compile Java to C, you might try compiling Java to machine code with GCJ, then disassembling the machine code, then (somehow?) converting the assembly code to C.

How do you call a function in C from Java?

To call a specific Java function from C, you need to do the following: Obtain the class reference using the FindClass(,,) method. Obtain the method IDs of the functions of the class that you want to call using the GetStaticMethodID and GetMethodID function calls.

What is Jnicall?

JNICALL contains any compiler directives required to ensure that the given function is treated with the proper calling convention.


1 Answers

The ">>>" is the unsigned right shift operator in Java. It can be replaced with ">>", which, however, sign-extends the value if it's negative. In this case, however, the use of the ">>" operator is harmless, since the result is reduced to a single byte in value (& 0x00FF).

The masking used in bytesToInt (& 0xFF000000 and so on) was necessary in Java because in Java, bytes are signed values, that is, they can be positive or negative, and converting to int can sign-extend a negative value. In C#, however, bytes can only be positive, so no masking is necessary. Thus, the bytesToInt method can be rewritten simply as:

return (((int)b0 << 24))    
  | (((int)b1 << 16))
  | (((int)b2 << 8))
  | ((int)b3);
like image 162
Peter O. Avatar answered Sep 30 '22 10:09

Peter O.