HexUtil
Introduction
Hexadecimal (abbreviated as hex or subscript 16) is a positional numeral system that uses 16 as its base, typically using the digits 0 through 9 and the letters A through F to represent values (where A~F represents 10~15). For example, the decimal number 57 is written as 111001 in binary and 39 in hexadecimal.
To distinguish between hexadecimal and decimal values in languages like Java and C, a prefix of 0x is added to hexadecimal numbers. For example, 0x20 represents the decimal value 32, not 20. HexUtil is a utility class for converting strings or byte arrays to and from hexadecimal representation.
Usage
Hexadecimal is often used to display binary values that cannot be displayed directly and is commonly used in:
- String representation of images
- Encryption and decryption
- Encoding conversion
Implementation
HexUtil mainly consists of two core methods: encodeHex
and decodeHex
, along with some overloaded methods for strings.
String str = "我是一个字符串";
String hex = HexUtil.encodeHexStr(str, CharsetUtil.CHARSET_UTF_8);
//hex is: e68891e698afe4b880e4b8aae5ad97e7aca6e4b8b2
String decodedStr = HexUtil.decodeHexStr(hex);
//decodedStr is the same as str