简体   繁体   English

DataInputStream readByte返回一个大值

[英]DataInputStream readByte is returning a big value

I'm creating a Chip-8 emulator that requires you to read virtual rom files in bytes. 我正在创建一个Chip-8仿真器,该仿真器要求您以字节为单位读取虚拟rom文件。 I have this code that is calling a readByte method. 我有这段代码正在调用readByte方法。 If you look at the values that this is printing out, some of them are regular bytes, and some of them are crazy big. 如果您查看打印出的值,则其中一些是常规字节,而另一些则非常疯狂。 在此处输入图片说明

DataInputStream.readByte() returns a byte which is a signed type . DataInputStream.readByte()返回一个byte ,该byte是带符号的类型 The returned value can be negative . 返回的值可以为

Integer.toHexString(intValue) returns a hex-representation of the value interpreted as an unsigned integer. Integer.toHexString(intValue)返回值的十六进制表示形式,该值表示为无符号整数。

Thus, positive values (like 76, 12) are printed as you expect, while negative values are printed in two's complement representation (the way negative values are represented in Java). 因此,将按您的期望打印正​​值(如76、12),而负数以二进制补码表示 (Java中负值的表示方式)。

For example, the printed value of fffffffe is a 32-bit (integer size) two's complement representation of -2 . 例如,打印的值fffffffe是一个32位(整数大小)的2的补码表示-2


To properly print byte values, use this: 要正确打印字节值,请使用以下命令:

System.out.println(String.format("%02x", tmp));

Note that this will also properly left-pad printed values with zeros. 请注意,这也将正确地将填充的值零左移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM