I have a program that I made in Python to find specific tags in TIFF IFD's and return the values. It was just a proof of concept thing in python, and now I need to move the functionality to java. I think I can just use the String(byteArray[])
constructor for the ASCII data types, but I still need to get Unsigned short (2 byte)
and unsigned long (4 byte)
values. I don't need to write them back to the file or modify them, all I need to do is get a Java Integer
or Long
object from them. This is easy in python with the struct
and mmap
classes, does any one know of a similar way in java? I looked at the DataInput
class, but the readUnsignedLong
method reads 8 bytes.
DataInputStream allows you to read shorts and longs. You should mask them with the appropriate bit mask (0xFFFF
for short, 0xFFFFFFFF
for 32 bit) in order to account for the difference between signed/unsigned types.
e.g.
// omits error handling
FileInputStream fis = ...;
DataInputStream stream = new DataInputStream(fis);
int short_value = 0xFFFF & stream.readShort();
long long_value = 0xFFFFFFFF & stream.readInt();
If you're sure that the data won't be towards the high end of the 2 byte field, or 4 byte field, you can forego the bit masking. Otherwise, you need to use a wider data type to account for the fact that unsigned values hold a larger range of values than their signed counterparts.
I looked at the DataInput class, but the
readUnsignedLong
method reads 8 bytes.
Java does not have unsigned types. It takes 4 bytes to make an int
, and 8 bytes to make a long
, unsigned or otherwise.
If you don't want to use DataInput
, you can read the bytes into byte arrays (byte[]
) and use a ByteBuffer
to turn those byte values into int
s and long
s with left padding. See ByteBuffer#getInt()
and ByteBuffer#getLong()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With