Convert int to unsigned short java

浪子不回头ぞ 提交于 2020-01-03 10:56:05

问题


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.


回答1:


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);



回答2:


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

int toUint32(short s)
{
    return s & 0xFFFF;
}



回答3:


You can extract single bytes from your integers with

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



回答4:


Use http://download.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html

dos.writeShort(value & 0xFFFF);


来源:https://stackoverflow.com/questions/6599548/convert-int-to-unsigned-short-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!