java:将整数作为无符号 8 位整数写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10756264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:25:18  来源:igfitidea点击:

java: writing integers to file as unsigned 8 bit integer

javaintegerunsigned

提问by Joel Feodiyoup

In java, how do I write integers to a file so that they are unsigned 8 bit integers (within range 0 to 255) ? Is it enough that the numbers are of type int and within 0-255, or do I need to convert them to some other type first? I think it's just the same thing? But I'm not sure if something funny happens when they get placed in the file...

在 java 中,如何将整数写入文件,以便它们是无符号 8 位整数(在 0 到 255 范围内)?数字的类型为 int 并且在 0-255 之间就足够了,还是我需要先将它们转换为其他类型?我认为这只是同一件事?但是我不确定当它们被放入文件时是否会发生一些有趣的事情......

回答by QuantumMechanic

Signed vs. unsigned is only a matter of how the bit patterns are interpreted, not the bit patterns themselves.

有符号与无符号只是如何解释位模式的问题,而不是位模式本身。

So if as long as your integers are in the range 0to 255, you can just jam them into bytes and write the bytes to a file.

因此,只要您的整数在0to范围内255,您就可以将它们塞入字节并将字节写入文件。

However, because Java interprets byte bit patterns as being signed, you have to be careful when reading them back in.

但是,因为 Java 将字节位模式解释为有符号的,所以在读回它们时必须小心。

For example, say you have the integer 253. This is (in full 32-bit form):

例如,假设您有整数253。这是(完整的 32 位形式):

00000000000000000000000011111101

If you do:

如果你这样做:

int i = 253;
byte b = (byte) i;

then bwill contain the bits:

然后b将包含位:

11111101

If you ask Java to use this, Java will claim it is -3because when interpreting bits as signed, -3is represented as the pattern 11111101. And so if you write that byte to a file, the bits 11111101will be written out, as desired.

如果您要求 Java 使用它,Java 会声称这是-3因为在将位解释为有符号时,-3表示为模式11111101。因此,如果您将该字节写入文件,11111101则会根据需要写出这些位。

Likewise, when you read it back in to a byte when reading the file, the byte you read it into will be filled with the bit pattern 11111101which, again, Java will interpret as -3. So you cannotjust do:

同样,当您在读取文件时将其读回一个字节时,您读入的字节将填充位模式11111101,Java 再次将其解释为-3. 所以你不能只做:

byte b = readByteFromFile();
int i = b;

because Java will interpret b's contents as -3and give you the integer that represents -3as a 32-bit integer, which will be:

因为 Java 会将b的内容解释为-3并为您提供表示-3为 32 位整数的整数,这将是:

11111111111111111111111111111101

Instead, you need to mask things off to make sure the integer you end up with is:

相反,您需要屏蔽一些东西以确保最终得到的整数是:

00000000000000000000000011111101

So,

所以,

byte b = readByteFromFile();
int i = (0x000000FF) & b;

回答by NPE

DataOutputStream.writeByte()will write the intas a 1-byte value.

DataOutputStream.writeByte()将写入int1 字节值。