Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to unsigned short java

I have written a .obj parser in java to modelize 3D objects on iPhone. I would like to export the data as a binary file, which must be as small as possible. I have plenty of indices that would fit a unsigned short, but they are represented as int in java.

I would like to use the ByteBuffer class to do the conversion just before writing the data in a file. I suppose I will have to manipulate bytes before pushing them into the ByteBuffer but I have no idea how to do so.

Thank you in advance if you can help me.

like image 974
Friedrik Avatar asked Jul 06 '11 16:07

Friedrik


2 Answers

In Java, an unsigned short can be represented as a char. Just cast the int to char and use putChar() on the ByteBuffer.

myBuffer.putChar((char) my16BitInt);
like image 84
Michael Myers Avatar answered Nov 11 '22 05:11

Michael Myers


short toUint16(int i)
{
    return (short) i;
}

int toUint32(short s)
{
    return s & 0xFFFF;
}
like image 23
Martijn Courteaux Avatar answered Nov 11 '22 04:11

Martijn Courteaux