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.
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 (
& 0xFF000000and so on) was necessary in Java because in Java, bytes are signed values, that is, they can be positive or negative, and converting tointcan 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: