[英]Java integer to fixed length byte array
How can I convert an integer between 0 and 65k to fixed length of two bytes? 如何将0到65k之间的整数转换为固定长度的两个字节? as an example
举个例子
2 would be 00000000 00000010
2将是
00000000 00000010
~65k would be 11111111 11111111
〜65k将是
11111111 11111111
and all that in a byte array 以及所有字节数组
java has the short data type, this is a 2 bytes integer. java具有短数据类型,这是2个字节的整数。 You cast the integer to short.
您将整数强制转换为short。
int a = 1;
short b = (short)a;
If you want the bytes of the integer you can use ByteBuffer 如果您想要整数的字节,则可以使用ByteBuffer
byte[] bytes = ByteBuffer.allocate(2).putShort((short)intnumber).array();
Or if you want the binary format you can just use toBinaryString method of the Integer. 或者,如果您想要二进制格式,则可以只使用Integer的toBinaryString方法。
int x = 2;
System.out.println(Integer.toBinaryString(x));
When x
is your number between 0 and 65,535 just use 当
x
是您介于0到65,535之间的数字时,请使用
new byte[] { (byte) (x >> 8), (byte) x }
to create a byte array containing the value as two bytes in big-endian format. 创建一个字节数组,该字节数组以big-endian格式包含两个字节的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.