gpt4 book ai didi

java - ByteArrayInputStream#read() 负输入字节的奇怪行为

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:31 25 4
gpt4 key购买 nike

我在测试中遇到了这段代码。

byte[] bytes = new byte[] { -1, 1, 0x0 }; 
InputStream in = new ByteArrayInputStream(bytes);
System.out.println(in.read() + in.read() + in.read());

我预计此代码会返回 0 (-1+1+0),但它会返回 256。

我很纳闷。

谁能解释一下这个行为?

附言

显示第一个语句返回 255。为什么?

最佳答案

试试这段代码,你就会明白为什么。

import java.io.ByteArrayInputStream;
import java.io.InputStream;


public class Test006 {

public static void main(String[] args) throws Exception {
byte[] bytes = new byte[] { -1, 1, 0x0 };
InputStream in = new ByteArrayInputStream(bytes);
System.out.println(in.read());
System.out.println(in.read());
System.out.println(in.read());
}

}

第一个数字被读取为 int 255,因此总和为 256。

值 -1 看起来像一个字节。
1111 1111

显然,当它被读取为一个 int 时,Java 不会添加前导 1
(保留将把它变成 int -1 的符号)但添加​​
前导零。所以这个 int 变成了:

0000 0000 0000 0000 0000 0000 1111 1111

这是 int 255 而不是 -1。

int -1 看起来像这样:

1111 1111 1111 1111 1111 1111 1111 1111

所以...这就是 int 255 的来源。

关于java - ByteArrayInputStream#read() 负输入字节的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22589528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com