1

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 (e.g. 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?

Community
  • 1
  • 1
Marc
  • 5,315
  • 5
  • 30
  • 36
  • 1
    Why is it so important you use a switch statement? Just use an `if` statement instead. Sounds like it'd prevent an unnecessary headache. – William Morrison Feb 16 '14 at 00:15
  • @William - I think it's cleaner and easier to read & extend to have a switch than a line of cascading if-else statements. – Marc Feb 17 '14 at 15:53

1 Answers1

2

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.

Dolda2000
  • 25,216
  • 4
  • 51
  • 92