gpt4 book ai didi

java - 为什么 ByteArrayOutputStream 和 ByteArrayInputStream 的内容不一样?

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

我在 Java 单元测试中遇到了一个大问题。我将字节数组与 InputStream 进行比较,但没有得到相同的结果。

例子如下。

public final class ByteGetInputStreamExampleProblem
{
public static void main( final String[] args ) throws Exception
{
final SecureRandom s = new SecureRandom() ;

final ByteArrayOutputStream bos = new ByteArrayOutputStream() ;

long bPut = 0 ;

final byte[] buffer = new byte[ 2 ] ;

while( bPut < 10 )
{
s.nextBytes( buffer ) ;
bos.write( buffer ) ;
bPut += buffer.length ;
}

final InputStream is = new ByteArrayInputStream( bos.toByteArray() ) ;

System.out.print("A = ");

for( int i = 0 ; i < bos.size() ; i++ )
System.out.print( bos.toByteArray()[i] + ";" ) ;

System.out.print("\nB = ");

int c ;
while( ( c = is.read() ) != -1 )
System.out.print(c + ":");
} ;
} ;

输出:

A = -3;-47;-121;37;-73;83;109;-54;20;106;

B = 253:209:135:37:183:83:109:202:20:106:

最佳答案

当您打印 A 的内容时,您将它们打印为字节。因此它将打印 Byte.MIN_VALUEByte.MAX_VALUE 之间的值(-128127)。

当您使用 is.read() 时,您读取的内容是作为 int 传递给您的无符号数字。此值介于 0255 之间。

您可以通过将 c 转换为一个字节来获得相同的输出,例如

while( ( c = is.read() ) != -1 ){
byte b = (byte)c;
System.out.print(b + ":");
}

本质上,您需要将两个数字转换为 0255 之间或 -128127.

您可以将 0255 范围转换为 -128127,方法是将其转换为字节。

您可以通过执行 value & 0xFF-128 转换为 127。这会将其更改为在 0-255 范围内。

ByteArrayInputStreamread()的代码如下:

public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}

关于java - 为什么 ByteArrayOutputStream 和 ByteArrayInputStream 的内容不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38092891/

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