十六进制是一种以16为基数的数制,用于以人类可读的形式表示二进制数据。每个字节由两个十六进制数字表示,范围为 0-9 和 a-f。
当需要以简单、易读的方式将原始二进制数据表示为文本时,使用十六进制。但当数据大小很重要时应避免使用,因为相比原始字节或更紧凑的编码(如 Base64),十六进制会使数据长度增加一倍。
# Encoding
printf 'Hello' | xxd -p
# Output: 48656c6c6f
# Decoding
printf '48656c6c6f' | xxd -r -p
# Output: Hello
// Encoding
let encoded = Buffer.from("Hello").toString("hex");
console.log(encoded);
// Output: 48656c6c6f
// Decoding
let decoded = Buffer.from("48656c6c6f", "hex").toString();
console.log(decoded);
// Output: Hello
package main
import (
"encoding/hex"
"fmt"
)
func main() {
// Encoding
encoded := hex.EncodeToString([]byte("Hello"))
fmt.Println(encoded)
// Output: 48656c6c6f
// Decoding
decoded, _ := hex.DecodeString("48656c6c6f")
fmt.Println(string(decoded))
// Output: Hello
}
// Encoding
$encoded = bin2hex("Hello");
echo $encoded . "\n";
// Output: 48656c6c6f
// Decoding
$decoded = hex2bin("48656c6c6f");
echo $decoded . "\n";
// Output: Hello