user3122536
user3122536

Reputation: 61

How to read unsigned values from files

I am trying to read binary data (Doom WAD files), which contain a lot of unsigned short and unsigned byte values.

At the moment I read the file into a byte[], wrap a ByteBuffer with little-endian order around it and access the values by bbuf.getShort() etc. respectively.

Converting those e. g. to 2D-coordinates is not a problem, because in the end it won't matter if they range eg. from -128 to 128 or from 0 to 256, but more often the short values are used as array indices and short/byte values as flags/, so I need a fast way to treat them as signed types. I know, Java doesn't have unsigned types "for sake of simplicity...". Can you make any suggestions?

Upvotes: 1

Views: 1665

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

If you need to interprete 0xFF byte as 256 do the following

int n = b & 0xFF;

Upvotes: 0

BambooleanLogic
BambooleanLogic

Reputation: 8161

If all else fails, you could always store them internally as ints and make sure you do proper conversion when reading/writing.

(Read as byte/short, cast to int, add 2^bits if negative. Just truncate to 8/16 bits when writing.)

Hardly the most elegant solution, I admit.

Upvotes: 0

Boris Brodski
Boris Brodski

Reputation: 8695

In order to save unsigned ints you need a long. Then you need to truncate last 32 bits. You can use following trick to do it.

final long UNSIGNED_INT_BITS = 0xffffffffL;
int a = -3;
long b = UNSIGNED_INT_BITS & a;
System.out.println(a);
System.out.println(b);
System.out.println(Long.toHexString(UNSIGNED_INT_BITS));

Output:

-3
4294967293
ffffffff

Upvotes: 1

Related Questions