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

☆樱花仙子☆ 提交于 2019-12-10 13:45:23

问题


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.


回答1:


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);



回答2:


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;
}


来源:https://stackoverflow.com/questions/6920993/converting-java-method-to-c-converting-bytes-to-integers-with-bit-shift-operat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!