二進制編碼

在網絡信道中,所有的數據都只能按照字節傳輸

 對所有的基本類型,均可以轉成byte[]

例如:

boolean byte[1]
short byte[2]
int byte[4]
float byte[4]
double byte[8]
long byte[8]
String byte[N]

ByteBuffer

import java.nio.ByteBuffer,可譯爲字節緩衝區

使用這個類,可以輕鬆完成二進制編解碼

ByteBuffer編碼過程

1、編譯時,首先創建一個ByteBuffer對象,

ByteBuffer bbuf = ByteBuffer.allocate(1000);

2、然後把數據塞進去

// 放入數據
bbuf.putInt(1234);
bbuf.putDouble(33.44);

3、查看編碼後的結果

// 查看編碼後的結果
int size = bbuf.position();  // 已經編碼的字節數
byte[] array = bbuf.array(); // 取得ByteBuffer的內部數組

package my;

import java.nio.ByteBuffer;

public class Test
{
	// 此工具方法用於按十六進制打印一個字節數組 ( 十六進制,參考《二進制篇》 )
	public static void print(byte[] array, int off, int length)
	{
		for(int i=0; i<length; i++)
		{
			int index = off + i;
			if(index >= array.length) break;
			
			if( i>0 && i%8 == 0)
				System.out.printf("\n");
			
			System.out.printf("%02X ", array[index]);			
		}
		System.out.printf("\n");
	}
	

	public static void main(String[] args)
	{
		// 注意:不支持 new ByteBuffer()來創建
		ByteBuffer bbuf = ByteBuffer.allocate(1000);
		
		// 放入數據
		bbuf.putInt(1234);
		bbuf.putDouble(33.44);
		
		// 查看編碼後的結果
		int size = bbuf.position();  // 已經編碼的字節數
		byte[] array = bbuf.array(); // 取得ByteBuffer的內部數組
		
		print (array, 0, 12);
		
		System.out.println("exit");
	}

}

 

發佈了228 篇原創文章 · 獲贊 20 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章