开发者

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 开发者_StackOverflow中文版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 (& 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);


You can use the BitConverter class to do conversions between base data types and byte arrays.

Rewriting the bytesToInt() method would look like the following:

public static int BytesToIntUsingBitConverter(byte b0, byte b1, byte b2, byte b3)
{
  var byteArray = BitConverter.IsLittleEndian ? new byte[] { b3, b2, b1, b0 } : new byte[] { b0, b1, b2, b3 };

  return BitConverter.ToInt32(byteArray, 0);
}

And rewriting the charToBytes() method would look like the following:

public static byte[] CharToBytesUsingBitConverter(char c)
{
  byte[] byteArray = BitConverter.GetBytes(c);
  return BitConverter.IsLittleEndian ? new byte[] { byteArray[1], byteArray[0] } : byteArray;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜