Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将java方法转换为C#:使用位移位运算符将字节转换为整数_C#_Java_Bit Manipulation - Fatal编程技术网

将java方法转换为C#:使用位移位运算符将字节转换为整数

将java方法转换为C#:使用位移位运算符将字节转换为整数,c#,java,bit-manipulation,C#,Java,Bit Manipulation,我正在尝试将以下两种方法转换为c#,而不让.net编译器向我抱怨。坦率地说,我只是不明白这两种方法在幕后是如何起作用的。因此,这里的答案和解释将是非常好的 public static int bytesToInt(byte b0, byte b1, byte b2, byte b3) { return (((int)b0 << 24) & 0xFF000000) | (((int)b1 << 16) & 0x00FF

我正在尝试将以下两种方法转换为c#,而不让.net编译器向我抱怨。坦率地说,我只是不明白这两种方法在幕后是如何起作用的。因此,这里的答案和解释将是非常好的

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;
}
public static int bytestpoint(字节b0、字节b1、字节b2、字节b3)
{
返回((int)b0 8)和0x00FF);
结果[1]=(字节)((c>>>0)和0x00FF);
返回结果;
}
第二种方法特别容易混淆,因为所使用的移位运算符与第一种方法不同

提前感谢您的帮助。

在Java中,“>>>”是未签名的右移运算符。它可以替换为“>>”,但是,如果值为负值,则符号会扩展该值。但是,在这种情况下,使用“>>”运算符是无害的,因为结果的值减少到一个字节(
&0x00FF

ByTestPoint(
&0xFF000000
等等)中使用的屏蔽在Java中是必要的,因为在Java中,字节是有符号的值,也就是说,它们可以是正数或负数,转换为
int
可以对负数进行符号扩展。然而,在C#中,字节只能是正数,因此不需要掩蔽。因此,ByTestPoint方法可以简单地重写为:

return (((int)b0 << 24))    
  | (((int)b1 << 16))
  | (((int)b2 << 8))
  | ((int)b3);
return(((int)b0您可以使用该类在基本数据类型和字节数组之间进行转换

重写
ByTestPoint()
方法如下所示:

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);
}
public static byte[] CharToBytesUsingBitConverter(char c)
{
  byte[] byteArray = BitConverter.GetBytes(c);
  return BitConverter.IsLittleEndian ? new byte[] { byteArray[1], byteArray[0] } : byteArray;
}
重写
charToBytes()
方法如下所示:

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);
}
public static byte[] CharToBytesUsingBitConverter(char c)
{
  byte[] byteArray = BitConverter.GetBytes(c);
  return BitConverter.IsLittleEndian ? new byte[] { byteArray[1], byteArray[0] } : byteArray;
}

Eric,你的回答很好,也很正确。谢谢你的努力。不客气。我非常喜欢让框架尽可能多地为我做工作。:)