Hex编码
什么是Hex编码
Hex编码是一种用16个字符表示任意二进制数据的方法。它是一种编码,而非加密。
Hex编码的代码实现和码表
1 2 3 4 5 6 7
| build.gradle dependencies { api 'com.squareup.okhttp3:okhttp:3.10.0' } ByteString byteString = ByteString.of("100".getBytes()); byteString.hex();
|
Hex编码特点
- 用0-9、A-F十六个字符表示。
- 每个十六进制字符代表4bit,也就是2个十六进制字符代表一个字节。
- 在实际应用中,比如密钥初始化,一定要分清楚传进去的密钥是什么编码,采用对应方式解析,才能得到正确的结果。
- 编程中的很多问题,需要从字节甚至二进制位角度去考虑,才能明白。
Java实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| static public String encode(byte[] binaryData) { if (binaryData == null) return null; int lengthData = binaryData.length; int lengthEncode = lengthData * 2; char[] encodedData = new char[lengthEncode]; int temp; for (int i = 0; i < lengthData; i++) { temp = binaryData[i]; if (temp < 0) temp += 256; encodedData[i*2] = lookUpHexAlphabet[temp >> 4]; encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf]; } return new String(encodedData); }
|