java_int数组转byte数组的一种方法

Java: int数组转byte数组的一种方法

记录一种int数组转byte数组的方法,无意中看到的。

之前都是通过移位操作完成的,现在发现通过系统API就能实现:

package com.yongdami.test;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Locale;

public class Test {

	static int[] INT_ARRY = new int[] { 0x1234, 0x5678, 0x9ABC, 0xDEF1 };

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// int 数组转 byte 数组(小端)
		byte[] result1 = intArrToByteArrLittleEndian();
		System.out.println("result1: " + printHexString(result1));

		// int 数组转 byte 数组(小端,采用JDK API)
		byte[] result2 = intArrToByteArrLittleEndianBySystemApi();
		System.out.println("result2: " + printHexString(result2));

		// int 数组转 byte 数组(大端)
		byte[] result3 = intArrToByteArrBigEndian();
		System.out.println("result3: " + printHexString(result3));

		// int 数组转 byte 数组(大端,采用JDK API)
		byte[] result4 = intArrToByteArrBigEndianBySystemApi();
		System.out.println("result4: " + printHexString(result4));

	}

	static byte[] intArrToByteArrLittleEndian() {
		byte[] byteArr = new byte[INT_ARRY.length * 4];

		int offset = 0;
		for (int i = 0; i < INT_ARRY.length; i++) {
			int value = INT_ARRY[i];
			byteArr[offset++] = (byte) (value & 0xFF);
			byteArr[offset++] = (byte) (value >> 8 & 0xFF);
			byteArr[offset++] = (byte) (value >> 16 & 0xFF);
			byteArr[offset++] = (byte) (value >> 24 & 0xFF);
		}

		return byteArr;
	}

	static byte[] intArrToByteArrLittleEndianBySystemApi() {
		ByteBuffer byteBuffer = ByteBuffer.allocate(INT_ARRY.length * 4);
		byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
		IntBuffer intBuffer = byteBuffer.asIntBuffer();
		intBuffer.put(INT_ARRY);
		return byteBuffer.array();
	}

	static byte[] intArrToByteArrBigEndian() {
		byte[] byteArr = new byte[INT_ARRY.length * 4];

		int offset = 0;
		for (int i = 0; i < INT_ARRY.length; i++) {
			int value = INT_ARRY[i];
			byteArr[offset++] = (byte) (value >> 24 & 0xFF);
			byteArr[offset++] = (byte) (value >> 16 & 0xFF);
			byteArr[offset++] = (byte) (value >> 8 & 0xFF);
			byteArr[offset++] = (byte) (value & 0xFF);
		}

		return byteArr;
	}

	static byte[] intArrToByteArrBigEndianBySystemApi() {
		ByteBuffer byteBuffer = ByteBuffer.allocate(INT_ARRY.length * 4);
		byteBuffer.order(ByteOrder.BIG_ENDIAN);
		IntBuffer intBuffer = byteBuffer.asIntBuffer();
		intBuffer.put(INT_ARRY);
		return byteBuffer.array();
	}

	static String printHexString(byte[] arr) {
		StringBuilder builder = new StringBuilder();
		for (byte b : arr) {
			String s = String.format(Locale.getDefault(), "%02X ", b & 0xFF);
			builder.append(s);
		}

		return builder.toString();
	}

}

输出:

result1: 34 12 00 00 78 56 00 00 BC 9A 00 00 F1 DE 00 00
result2: 34 12 00 00 78 56 00 00 BC 9A 00 00 F1 DE 00 00
result3: 00 00 12 34 00 00 56 78 00 00 9A BC 00 00 DE F1
result4: 00 00 12 34 00 00 56 78 00 00 9A BC 00 00 DE F1

posted @ 2023-03-16 10:35  夜行过客  阅读(1100)  评论(0编辑  收藏  举报