将 int 转换为 unsigned short java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6599548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert int to unsigned short java
提问by Friedrik
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.
我已经用 java 编写了一个 .obj 解析器来对 iPhone 上的 3D 对象进行建模。我想将数据导出为二进制文件,该文件必须尽可能小。我有很多适合 unsigned short 的索引,但它们在 java 中表示为 int。
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.
我想在将数据写入文件之前使用 ByteBuffer 类进行转换。我想我必须在将字节推入 ByteBuffer 之前对其进行操作,但我不知道该怎么做。
Thank you in advance if you can help me.
如果您能帮助我,请提前感谢您。
回答by Michael Myers
In Java, an unsigned short can be represented as a char
. Just cast the int to char and use putChar()
on the ByteBuffer.
在 Java 中,unsigned short 可以表示为char
. 只需将 int 转换为 char 并putChar()
在 ByteBuffer 上使用。
myBuffer.putChar((char) my16BitInt);
回答by Martijn Courteaux
short toUint16(int i)
{
return (short) i;
}
int toUint32(short s)
{
return s & 0xFFFF;
}
回答by Darcara
You can extract single bytes from your integers with
您可以从整数中提取单个字节
int i;
byte b1 = i & 0xFF;
byte b2 = (i >> 8) & 0xFF;
回答by Leonard Brünings
Use http://download.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html
使用 http://download.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html
dos.writeShort(value & 0xFFFF);