Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java整数到固定长度字节数组_Java_Integer_Byte - Fatal编程技术网

Java整数到固定长度字节数组

Java整数到固定长度字节数组,java,integer,byte,Java,Integer,Byte,如何将0到65k之间的整数转换为两个字节的固定长度?例如 2将是00000000000010 ~65k等于11111111111 字节数组中的所有数据类型都是短数据类型,这是一个2字节的整数。将整数强制转换为短整数 int a = 1; short b = (short)a; 如果需要整数的字节,可以使用ByteBuffer 或者,如果需要二进制格式,可以使用整数的toBinaryString方法 int x = 2; System.out.println(Integer.toBinarySt

如何将0到65k之间的整数转换为两个字节的固定长度?例如

2将是00000000000010

~65k等于11111111111

字节数组中的所有数据类型都是短数据类型,这是一个2字节的整数。将整数强制转换为短整数

int a = 1;
short b = (short)a;
如果需要整数的字节,可以使用ByteBuffer

或者,如果需要二进制格式,可以使用整数的toBinaryString方法

int x = 2;
System.out.println(Integer.toBinaryString(x));
当x是介于0和65535之间的数字时,只需使用

new byte[] { (byte) (x >> 8), (byte) x }

创建一个字节数组,其中包含两个字节的big-endian格式的值。

我编辑了我的答案我想中间的一个是我要找的,但它在我的情况下引发了一个BufferOverflow异常是的,只需使用ByteBuffer.allocate2.PutShort1;
new byte[] { (byte) (x >> 8), (byte) x }