简体   繁体   中英

Java integer to fixed length byte array

How can I convert an integer between 0 and 65k to fixed length of two bytes? as an example

2 would be 00000000 00000010

~65k would be 11111111 11111111

and all that in a byte array

java has the short data type, this is a 2 bytes integer. You cast the integer to short.

int a = 1;
short b = (short)a;

If you want the bytes of the integer you can use 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.

int x = 2;
System.out.println(Integer.toBinaryString(x));

When x is your number between 0 and 65,535 just use

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

to create a byte array containing the value as two bytes in big-endian format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM