简体   繁体   中英

Compare a 4 byte usigned integer (from file) with a defined integer value in java

I have a file that contains data to read in little-endian binary format. To parse the file, I first read a 4-byte unsigned integer, then depending on the value of that integer, I execute different read routines.

Using ByteBuffer and this answer , I can read a 4 byte unsigned int as a long. But in my code, I would like to use a switch statement, and java does not allow switches on longs.

Since I'm just checking for equality, it would be fine to read the 4 bytes as a signed integer and compare it to my known value. However, my reference values are all defined as unsigned ints (eg 0xc15ab354). Is there a good way to convert these to signed ints (yes, it could be done manually, but this introduces the possibility of error) for comparison, or a better way to do the comparison?

That's quite simple. If you just use 0xc15ab354 as an int literal, you'll get the signed integer with that exact binary representation, so you can use it directly in your switch statement, just as it is.

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