C#和java之间输出的差异

Sla*_*ast 1 c# java

我正在尝试为C#中的函数编写Java等价物.代码如下.

在C#中:

byte[] a = new byte[sizeof(Int32)];
readBytes(fStream, a, 0, sizeof(Int32)); //fstream is System.IO.Filestream
int answer = BitConverter.ToInt32(a, 0);
Run Code Online (Sandbox Code Playgroud)

在Java中:

InputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte[] a = new byte[4];
readBytes(in, a, 0, 4);
int answer = byteArrayToInt(a);
Run Code Online (Sandbox Code Playgroud)

Java和C#:

int readBytes(Stream stream, byte[] storageBuffer, int offset, int requiredCount)
        {
            int totalBytesRead = 0;
            while (totalBytesRead < requiredCount)
            {
                int bytesRead = stream.Read(
                                storageBuffer,
                                offset + totalBytesRead,
                                requiredCount - totalBytesRead);
                if (bytesRead == 0)
                {
                    break; // while
                }

                totalBytesRead += bytesRead;
            }

            return totalBytesRead;
        }
Run Code Online (Sandbox Code Playgroud)

输出:

In C#: answer = 192  (Correct)  
In JAVA: answer = -1073741824 
Run Code Online (Sandbox Code Playgroud)

两者有所不同.我正在从文件输入流中读取,该文件输入流被编码并解析前四个字节.C#代码似乎产生192这是正确答案,而Java产生-1073741824,这是错误的答案.为什么以及如何?

编辑

这是我的byteArrayToInt

public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }
Run Code Online (Sandbox Code Playgroud)

解决 方案byteArrayToInt的正确解决方案

public static int byteArrayToInt(byte[] b) 
    {
        long value = 0;
        for (int i = 0; i < b.length; i++)
        {
           value += (b[i] & 0xff) << (8 * i);
        }
        return (int) value;
    }
Run Code Online (Sandbox Code Playgroud)

这给出了正确的输出

sou*_*eck 10

在java中,字节是有符号的,因此java字节中的-64二进制等效于c#byte中的192(192 == 256 - 64).

问题是probaby byteArrayToInt(),你认为它在转换过程中是无符号的.

一个简单的

 `b & 0x000000FF`
Run Code Online (Sandbox Code Playgroud)

在这种情况下可能有帮助.