二进制编码

在网络信道中,所有的数据都只能按照字节传输

 对所有的基本类型,均可以转成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");
	}

}

发布了246 篇原创文章 · 获赞 22 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/gjs935219/article/details/103314667