Convert int to unsigned short java

I wrote a .obj parser in java to simulate 3D objects on an iPhone. I would like to export the data as a binary file, which should be as small as possible. I have many indexes that will correspond to unsigned short sign, but they are represented as int in java.

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

Thanks in advance if you can help me.

+6
source share
4 answers

In Java, an unsigned character can be represented as a char . Just enter int in char and use putChar() in ByteBuffer.

 myBuffer.putChar((char) my16BitInt); 
+11
source
 short toUint16(int i) { return (short) i; } int toUint32(short s) { return s & 0xFFFF; } 
+3
source

You can extract single bytes from your integers with

 int i; byte b1 = i & 0xFF; byte b2 = (i >> 8) & 0xFF; 
+2
source

Source: https://habr.com/ru/post/892154/


All Articles