1-Hex编码
发布时间:2023-02-16 13:47:44 所属栏目:Java 来源:互联网
导读:编码原理 Hex编码就是把一个8位的字节数据用两个十六进制数展示出来,编码时,将8位二进制码重新分组成两个4位的字节,其中一个字节的低4位是原字节的高四位,另一个字节的低4位是原数据的低4位,高4位都补0,然后输出这两个字节对应十六进制数字作为编码。H
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ! -1 " -1 # -1 $ -1 % -1 & -1 ' -1 ( -1 ) -1 * -1 + -1,-1 - -1 . -1 / -1 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 : -1 ; -1 < -1 = -1 > -1 ? -1 @ -1 A 10 B 11 C 12 D 13 E 14 F 15 G -1 H -1 I -1 J -1 K -1 L -1 M -1 N -1 O -1 P -1 Q -1 R -1 S -1 T -1 U -1 V -1 W -1 X -1 Y -1 Z -1 [ -1 -1 ] -1 ^ -1 _ -1 ` -1 a 10 b 11 c 12 d 13 e 14 f 15 g -1 h -1 i -1 j -1 k -1 l -1 m -1 n -1 o -1 p -1 q -1 r -1 s -1 t -1 u -1 v -1 w -1 x -1 y -1 z -1 { -1 | -1 } -1 ~ -1 -1 解码的过程实际上就是获取连续两个字节,取这两个字节解码表中对应的数值,然后将这两个数值拼接成一个8位二进制码,作为解码的输出。源码如下: public int decode( byte[] data,int off,int length,OutputStream out) throws IOException { byte b1,b2; int outLen = 0; int end = off + length; while (end > off) { if (!ignore((char)data[end - 1])) { break; } end--; } int i = off; while (i < end) { while (i < end && ignore((char)data[i])) { i++; } b1 = decodingTable[data[i++]]; while (i < end && ignore((char)data[i])) { i++; } b2 = decodingTable[data[i++]]; if ((b1 | b2) < 0) { throw new IOException("invalid characters encountered in Hex data"); } out.write((b1 << 4) | b2); outLen++; } return outLen; } 其中ignore方法的代码如下,解码时会忽略首、尾及中间的空白。 private static boolean ignore( char c) { return c == 'n' || c =='r' || c == 't' || c == ' '; } 示例代码中的Hex工具类持有HexEncoder的实例,并通过ByteArrayOutputStream类实现对byte数组的操作,此外不再赘述。 public class Hex { private static final Encoder encoder = new HexEncoder(); public static byte[] encode( byte[] data,int off,int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data,off,length,bOut); } catch (Exception e) { throw new EncoderException("exception encoding Hex string: " + e.getMessage(),e); } return bOut.toByteArray(); } ...... (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |