Question

I have a well defined binary data and I want to write Java API for it.
The file format is like

File Signature     char[4]               4 bytes 
File Source ID     unsigned short        2 bytes
Header Size        unsigned long         4 bytes
Max                double                8 bytes

I am using DataInputStream for parsing the data. char is easy to parse, no problem. But unsigned cannot be parsed correctly.
I know Java has no unsigned number. How do I convert it? (Please take unsigned long as example).

EDIT

Here is the code I worte:

File file = new File("lidar.las");

DataInputStream in= new DataInputStream(new FileInputStream(file));

in.skipBytes(6);

long read = (long) (in.readInt() & 0xFFFFFFFFL);

System.out.println("read " + read);


the output is

read 3288596480

my expected number is 1220 .I do not know the code that wrote this binary record, probably in c. All I want is writing a Java version to read data out.

Solved
I am not sure I can answer my own question. LOL
Anyway, Here is the solutions.

private static int getSignedInt( final int unsignedInt ){

    ByteBuffer bb=ByteBuffer.allocate(1024*4);

    bb.putInt(unsignedInt).flip();

    int result =bb.order(ByteOrder.LITTLE_ENDIAN).getInt();
    bb.clear();

    return  result;
}
Was it helpful?

Solution

DataInputStream reads bytes in Big Endian orientation, but check this out:

3288596480 = 0xC4040000

Reversing the bytes, you get 0x04C4 = 1220

You just have to read the values in Little Endian. The question about the sign turns out to be a red herring.

OTHER TIPS

Just read them as short (2 bytes - Java) and int (4 bytes - Java) in your
Java code. You will not lose any information. If you need to output them later,
do a conversion so that you don't output signed numbers.

Given their names: File Source ID and Header Size I doubt you
will do any arithmetic operations on them. If you do, be careful.

Alternatively, you can read them both in long (8 bytes in Java),
and not worry about arithmetic operations as they will not cause issues.

Alternatively, you can read your values as byte arrays in Java,
and then transform them to the proper types in your Java code.
This is probably the most explicit and clean solution.
But it requires more coding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top