Conversion between Java integers and byte arrays

Source: Internet
Author: User

The programs that you do sometimes need to be used,

Record the

public class Numberutil {/** * int integer to 4 byte array * * @param i * integer * @return byte array/public
		Static byte[] IntToByte4 (int i) {byte[] targets = new BYTE[4];
		TARGETS[3] = (byte) (I & 0xFF);
		TARGETS[2] = (byte) (I >> 8 & 0xFF);
		TARGETS[1] = (byte) (I >> & 0xFF);
		Targets[0] = (byte) (I >> & 0xFF);
	return targets; /** * Long Integer to 8-byte byte array * * @param lo * Long integer * @return byte array/public static byte[] Lon
		GToByte8 (Long lo) {byte[] targets = new BYTE[8];
			for (int i = 0; i < 8; i++) {int offset = (Targets.length-1-i) * 8;
		Targets[i] = (byte) ((Lo >>> offset) & 0xFF);
	return targets; /** * Short integer to 2-byte byte array * * @param s * Short integer * @return byte array/public static byte[] UN
		SignedShortToByte2 (int s) {byte[] targets = new BYTE[2];
		Targets[0] = (byte) (S >> 8 & 0xFF); TARGETS[1] = (byte) (S & 0xFF);
	return targets; /** * byte array converted to unsigned short integer * * @param bytes * byte array * @return short integer */public static int by
	Te2tounsignedshort (byte[] bytes) {return Byte2tounsignedshort (bytes, 0);  /** * byte array converted to unsigned short integer * * @param bytes * Byte array * @param off * start position * @return
		Short integer */public static int byte2tounsignedshort (byte[] bytes, int off) {int high = Bytes[off];
		int low = Bytes[off + 1]; Return (High << 8 & 0xff00) |
	(Low & 0xFF); /** * byte array converted to int integer * * @param bytes * Byte array * @param off * start position * @return int integer
		Number */public static int byte4toint (byte[] bytes, int off) {int b0 = Bytes[off] & 0xFF;
		int B1 = Bytes[off + 1] & 0xFF;
		int b2 = Bytes[off + 2] & 0xFF;
		int B3 = Bytes[off + 3] & 0xFF; Return (B0 << 24) | (B1 << 16) | (B2 << 8) |
	B3; }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.