ByteBuf转为String、String转ByteBuf、String转byte[]数组
1.ByteBuf转String
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
ByteBuf buf = packet.content();
String con = ByteBufUtil.hexDump(buf);
log.info("转为字符串的数据为:{}",con);
}
2.String转ByteBuf
public static ByteBuf strToByteBuf(String con){
if (con != null && !con.equals("")){
byte[] bytes = ParseUtil.hexStringToBytes(con);
ByteBuf buf = Unpooled.wrappedBuffer(bytes);
}
}
3.String转byte[]数组
public static byte[] hexStringToBytes(String hexString) {
if (StringUtils.isEmpty(hexString)) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}