简体   繁体   中英

DataInputStream readByte is returning a big value

I'm creating a Chip-8 emulator that requires you to read virtual rom files in bytes. I have this code that is calling a readByte method. 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 . The returned value can be negative .

Integer.toHexString(intValue) returns a hex-representation of the value interpreted as an unsigned integer.

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).

For example, the printed value of fffffffe is a 32-bit (integer size) two's complement representation of -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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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