1.用netty給裝置發送封包
/*
obj:byte數組
*/
private void writeMessage(ChannelHandlerContext ctx, byte[] obj) {
ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf傳輸
bufff.writeBytes(obj);//對接需要16進制
ctx.writeAndFlush(bufff).addListener(new ChannelFutureListener() { //擷取目前的handle
@Override
public void operationComplete(ChannelFuture future) throws Exception {
StringBuilder sb = new StringBuilder("");
if (future.isSuccess()) {
log.info(sb.toString() + "回寫成功.");
} else {
log.error(sb.toString() + "回寫失敗.");
}
}
});
}
2.将16進制字元轉換為位元組
//将16進制的字元串轉成字元數組
public static byte[] getHexBytes(String str) {
str = str.replaceAll(" ", "");
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
}
return bytes;
}
3.将16位元組數組進制轉換為字元
//将16進制的byte數組轉換成字元串
public static String getBufHexStr(byte[] raw) {
String HEXES = "0123456789ABCDEF";
if (raw == null) {
return null;
}
final StringBuilder hex = new StringBuilder(2 * raw.length);
for (final byte b : raw) {
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}