2017-11-25 248 views
0

我用ByteArrayOutputStream填充了一个字节数组。当我打印它时,输出很混乱。我需要一些指导。从bytearrayoutputstream填充打印字节数组

这里是我的代码:

ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
    DataOutputStream out = new DataOutputStream(bout); 
    try { 
     out.writeInt(150); 
     byte[] b = bout.toByteArray(); 
     System.out.println(Arrays.toString(b)); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

这里是我的输出:

[0, 0, 0, -106] 

请帮

回答

0

150等于1001 0110 这是在字节的位-128项(最左边的位)加2 + 4 + 16 = -106

0

你写int 150至out。在二进制(具体地,two's complement),此整数看起来像这样:

0000 0000 0000 0000 0000 0000 1001 0110 

每组8个比特是一个字节的数据,类似于byte数据类型。但是,与所有Java的整数类型(char除外)一样,byte也被签名。因此,即使最后一个byte的二进制值为1001 0110,它也会显示为-106,这是二进制补码中该字节的正确值。您可以用下列语句替换您的打印语句:

String[] strings = new String[b.length]; 
for (int i = 0; i < b.length; i++) { 
    strings[i] = Integer.toString(Byte.toUnsignedInt(b[i])); 
} 
System.out.println("[" + String.join(", ", strings) + "]"); 

将以无符号格式打印字节;每个人都会在[0,255]的范围内。