Netty:利用ByteBufUtil将ByteBuf数据转换为美化过的十六进制表示

说明

利用io.netty.buffer.ByteBufUtil的appendPrettyHexDump函数,可以将ByteBuf的内容转换为美化过的多行表示的十六进制数据。

  • appendPrettyHexDump(StringBuilder dump, ByteBuf buf):在StringBuilder后面附加ByteBuf内容的多行表示的美化过的十六进制表示。
  • appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length):在StringBuilder后面附加ByteBuf部分内容的多行表示的美化过的十六进制表示。其中选取buffer的内容从offset位置处开始,长度为length个字节。

代码示例

用appendPrettyHexDump(StringBuilder dump, ByteBuf buf)函数转化

package com.thb;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

public class Demo {

	public static void main(String[] args) {
		// 创建一个ByteBuf
		ByteBuf buf = Unpooled.buffer();		

		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x68);
		}
		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x23);
		}
		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x30);
		}
		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x16);
		}		
		
		StringBuilder dump = new StringBuilder();
		// 在dump后面附加buffer内容的多行表示的美观的十六进制表示
		ByteBufUtil.appendPrettyHexDump(dump, buf);
		System.out.println(dump);
	}

}

运行输出:

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 68 68 68 68 68 68 68 68 68 23 23 23 23 23 23 |hhhhhhhhhh######|
|00000010| 23 23 23 23 30 30 30 30 30 30 30 30 30 30 16 16 |####0000000000..|
|00000020| 16 16 16 16 16 16 16 16                         |........        |
+--------+-------------------------------------------------+----------------+

用appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length)函数转化

package com.thb;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

public class Demo {

	public static void main(String[] args) {
		// 创建一个ByteBuf
		ByteBuf buf = Unpooled.buffer();		

		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x68);
		}
		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x23);
		}
		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x30);
		}
		for (int i = 0; i < 10; i++) {
			buf.writeByte(0x16);
		}		
		
		StringBuilder dump = new StringBuilder();
		// 在dump后面附加buffer内容的多行表示的美观的十六进制表示,从
		// 位置9处的数据开始,取20个字节的数据
		ByteBufUtil.appendPrettyHexDump(dump, buf, 9, 20);
		System.out.println(dump);
	}

}

运行输出:

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 23 23 23 23 23 23 23 23 23 23 30 30 30 30 30 |h##########00000|
|00000010| 30 30 30 30                                     |0000            |
+--------+-------------------------------------------------+----------------+

你可能感兴趣的:(java,开发语言,Netty)