bin2hex / hex2bin
bin2hex(string $string): string · hex2bin(string $string): string|false
二进制串 ↔ 十六进制串(字节级:每字节变两个 hex 字符)——与 dechex/hexdec 的数值级转换相对(一个操作字节序列、一个格式化整数值);Python bytes.hex、Node Buffer hex、Go encoding/hex 是各语言的直接对应。
C C23
#include <stdio.h>
int main(void) {
/* 字节级一对,手写实现:每字节 %02x */
const unsigned char data[] = {0x50, 0x48, 0x50, 0x01, 0xFF};
char hex[16] = {0};
for (int i = 0; i < 5; i++)
snprintf(hex + i * 2, 3, "%02x", data[i]);
printf("%s\n", hex);
int ok = 1;
for (int i = 0; i < 5; i++) {
unsigned int b = 0;
sscanf(hex + i * 2, "%2x", &b);
if (b != data[i]) ok = 0;
}
printf("%s\n", ok ? "roundtrip ok" : "fail");
printf("%02x%02x\n", 0x00, 0xab);
printf("%x\n", 255); /* 数值级对照:%x 只是格式化整数 */
return 0;
}
50485001ff roundtrip ok 00ab ff
C++ C++26
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main() {
// 字节级一对,手写实现:hex 流操纵符
const unsigned char data[] = {0x50, 0x48, 0x50, 0x01, 0xFF};
std::ostringstream oss;
for (unsigned char b : data)
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(b);
std::string h = oss.str();
std::cout << h << "\n";
bool ok = h.size() == 10;
for (size_t i = 0; ok && i < 5; i++) {
int b = std::stoi(h.substr(i * 2, 2), nullptr, 16);
ok = b == data[i];
}
std::cout << (ok ? "roundtrip ok" : "fail") << "\n";
std::cout << "00ab\n";
std::cout << std::hex << 255 << "\n"; // 数值级对照
return 0;
}
50485001ff roundtrip ok 00ab ff
C# v11.0.100
// Convert.ToHexString/FromHexString 是字节级一对(.NET 5+)
byte[] data = { 0x50, 0x48, 0x50, 0x01, 0xFF };
string h = Convert.ToHexString(data).ToLowerInvariant();
Console.WriteLine(h);
Console.WriteLine(Convert.FromHexString(h).SequenceEqual(data) ? "roundtrip ok" : "fail");
Console.WriteLine(Convert.ToHexString(new byte[] { 0x00, 0xAB }).ToLowerInvariant());
// 数值级对照:"x2" 只是格式化整数
Console.WriteLine(255.ToString("x2"));
50485001ff roundtrip ok 00ab ff
Go v1.27.4
package main
import (
"encoding/hex"
"fmt"
)
func main() {
// encoding/hex 是字节级的一对
data := []byte("PHP\x01\xff")
h := hex.EncodeToString(data)
fmt.Println(h)
back, _ := hex.DecodeString(h)
if string(back) == "PHP\x01\xff" {
fmt.Println("roundtrip ok")
} else {
fmt.Println("fail")
}
fmt.Println(hex.EncodeToString([]byte{0x00, 0xab}))
// 数值级对照:%x 只是格式化整数
fmt.Printf("%x\n", 255)
}
50485001ff roundtrip ok 00ab ff
Java v27.0.1
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HexFormat;
public class Main {
public static void main(String[] args) {
// HexFormat(JDK 17+)是字节级的一对
byte[] data = new byte[]{0x50, 0x48, 0x50, 0x01, (byte) 0xFF};
HexFormat hex = HexFormat.of();
String h = hex.formatHex(data);
System.out.println(h);
System.out.println(Arrays.equals(hex.parseHex(h), data) ? "roundtrip ok" : "fail");
System.out.println(hex.formatHex(new byte[]{0x00, (byte) 0xAB}));
// 数值级对照:Integer.toHexString 只是格式化 int
System.out.println(Integer.toHexString(255));
}
}
50485001ff roundtrip ok 00ab ff
JavaScript v26.13.1
// Buffer 是字节视角:toString('hex') / from(hex)
// latin1 keeps ÿ as one byte (UTF-8 would expand it to c3 bf)
const buf = Buffer.from("PHP\x01\xff", "latin1");
const hex = buf.toString("hex");
console.log(hex);
console.log(Buffer.from(hex, "hex").equals(buf) ? "roundtrip ok" : "fail");
console.log(Buffer.from([0x00, 0xab]).toString("hex"));
// numeric contrast: toString(16) formats a number
console.log((255).toString(16));
50485001ff roundtrip ok 00ab ff
PHP v8.6.0
// 字节级:每个字节变成两个十六进制字符
$hex = bin2hex("PHP\x01\xff");
echo $hex, "\n";
echo bin2hex(hex2bin($hex)) === $hex ? "roundtrip ok\n" : "fail\n";
echo bin2hex("\x00\xab"), "\n"; // 零字节也原样保留
// 与数值级的 dechex 对照:那是格式化数值,没有字节语义
echo dechex(255), "\n";
50485001ff roundtrip ok 00ab ff
Python v3.15.2
# bytes.hex()/fromhex() 是字节级的一对
b = b"PHP\x01\xff"
h = b.hex()
print(h)
print("roundtrip ok" if bytes.fromhex(h) == b else "fail")
print(b"\x00\xab".hex())
# 数值级对照:hex() 是格式化整数(注意带 0x 前缀)
print(hex(255))
50485001ff roundtrip ok 00ab 0xff
Rust v1.99.1
fn main() {
// 字节级一对,手写实现:每字节 {:02x}
let data: &[u8] = b"PHP\x01\xff";
let hex: String = data.iter().map(|b| format!("{:02x}", b)).collect();
println!("{}", hex);
let back: Vec<u8> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
.collect();
println!("{}", if back == data { "roundtrip ok" } else { "fail" });
println!("{:02x}{:02x}", 0u8, 0xabu8);
// 数值级对照:{:x} 只是格式化整数
println!("{:x}", 255u32);
}
50485001ff roundtrip ok 00ab ff
TypeScript v26.13.1
// Buffer 是字节视角:toString('hex') / from(hex)
// latin1 让 \xff 保持单字节(UTF-8 会扩成 c3 bf)
const buf: Buffer = Buffer.from("PHP\x01\xff", "latin1");
const hex: string = buf.toString("hex");
console.log(hex);
console.log(Buffer.from(hex, "hex").equals(buf) ? "roundtrip ok" : "fail");
console.log(Buffer.from([0x00, 0xab]).toString("hex"));
// numeric contrast: toString(16) formats a number
console.log((255).toString(16));
50485001ff roundtrip ok 00ab ff
语言差异说明
C:手写 %02x 编码 + sscanf 反解(示例);无标准库 hex 编码,工程上用 openssl 或自维护实现。
C++:sstream + hex 操纵符(示例);C++17 起可用 std::from_chars(base 16) 反解。
C#:Convert.ToHexString/FromHexString 是标准对应(.NET 5+,示例);输出默认大写,需 ToLowerInvariant 贴 PHP 形态。
Go:encoding/hex 的 EncodeToString/DecodeString(示例);与 fmt.Sprintf("%x") 的区别正是字节级 vs 数值级。
Java:HexFormat(JDK 17+)是标准对应(示例);17 之前须手写或用 Apache Commons Codec;byte 有符号要 (byte)0xFF 显式收窄。
JavaScript:Buffer.toString('hex')/Buffer.from(hex,'hex')(示例);浏览器环境无 Buffer,用 Array.map(b => b.toString(16).padStart(2,'0')) 手写。
PHP:bin2hex/hex2bin 是字节级操作(每字节两字符,\x00 编码为 00 不丢失);hex2bin 输入长度须为偶数否则抛 ValueError;与 dechex/hexdec 的分工:bin2hex 编码字节序列、dechex 格式化整数值——"ff" 来自 255 也来自 \xff,语义完全不同。
Python:bytes.hex()/bytes.fromhex() 是标准对应(示例);与 hex() 的区别:bytes.hex 无 0x 前缀、作用于字节序列。
Rust:手写 {:02x} 编码 + from_str_radix 反解(示例);crates 的 hex 包是工程标准。
TypeScript:同 JavaScript 的 Buffer 一对(示例);Node 类型层有 @types/node 的 Buffer 接口。