为什么从文件中读取的字节在Java和VB.NET之间不同?

huangapple go评论65阅读模式
英文:

Why are bytes read from a file different between Java and VB.NET?

问题

我读取文件 file.dat 的数据。

这是我在 VB.NET 中的代码:

Dim data() As Byte = File.ReadAllBytes("F:\test.dat")

这是我在 Android 中的代码:

String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/test.dat";
File file = new File(fileName);
byte[] writeBuf = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(writeBuf);
fis.close();

这些是结果:Java 和 VB.NET 之间的一些字节值是不同的。

为什么 Java 和 VB.NET 之间的字节值会不同呢?

为什么从文件中读取的字节在Java和VB.NET之间不同?

为什么 Java 和 VB.NET 之间的字节值会不同呢?

英文:

I read data of a file.dat.

This is my code in VB.NET:

Dim data() As Byte = File.ReadAllBytes("F:\test.dat")

This is my code in android:

String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/test.dat";
File file = new File(fileName);
byte[] writeBuf= new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(writeBuf);
fis.close();

These are results: some bytes are different between Java and VB.NET

为什么从文件中读取的字节在Java和VB.NET之间不同?

Why are the byte values are different between Java and VB.NET?

答案1

得分: 2

看到这些值,似乎只是一个有符号/无符号字节的问题。

有符号字节是 -128 到 127(在您的 Java 上下文中使用),而无符号字节是 0 到 255(在您的 .Net 上下文中使用)。

请注意,在两个上下文之间的数字不同的地方,如果将它们相加,它们会总和为 256(无论有符号/无符号,字节的最大值)。 (例如 154 + 102 = 256 和 217 + 39 = 256)。因此,数据本质上是相同的,只是由于受支持的数据类型范围不同而表示不同。

Java 没有无符号字节。

英文:

Looking at those values it appears that it's simply a signed/unsigned byte problem.

Signed Byte being -128 to 127 (used in your Java context) and Unsigned Byte being 0 to 255 (used in your .Net context).

Notice that where the numbers are different between the two contexts, if you add them, they sum to 256 (the maximum number of value for a byte regardless of signed/unsigned). (e.g. 154 + 102 = 256 and 217 + 39 = 256). So, the data is essentially the same, just represented differently given the supported datatype range.

Java doesn't have an unsigned byte.

huangapple
  • 本文由 发表于 2020年8月18日 12:21:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63461836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定