bin2hex / hex2bin

bin2hex(string $string): string · hex2bin(string $string): string|false

Binary string to hex string and back (byte level: every byte becomes two hex characters) — the counterpart of numeric-level dechex/hexdec (byte sequences vs formatting an integer); Python bytes.hex, Node Buffer hex and Go encoding/hex are the direct equivalents.

C C23

C23
#include <stdio.h>

int main(void) {
    /* byte-level pair, hand-rolled: %02x per byte */
    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); /* numeric contrast: %x formats an integer */
    return 0;
}
Output
50485001ff
roundtrip ok
00ab
ff

C++ C++26

C++26
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    // byte-level pair, hand-rolled: hex stream manipulator
    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"; // numeric contrast
    return 0;
}
Output
50485001ff
roundtrip ok
00ab
ff

C# v11.0.100

v11.0.100
// Convert.ToHexString/FromHexString are the byte-level pair (.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());
// numeric contrast: "x2" formats an integer
Console.WriteLine(255.ToString("x2"));
Output
50485001ff
roundtrip ok
00ab
ff

Go v1.27.4

v1.27.4
package main

import (
	"encoding/hex"
	"fmt"
)

func main() {
	// encoding/hex is the byte-level pair
	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}))
	// numeric contrast: %x formats an integer
	fmt.Printf("%x\n", 255)
}
Output
50485001ff
roundtrip ok
00ab
ff

Java v27.0.1

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+) is the byte-level pair
        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}));
        // numeric contrast: Integer.toHexString formats an int
        System.out.println(Integer.toHexString(255));
    }
}
Output
50485001ff
roundtrip ok
00ab
ff

JavaScript v26.13.1

v26.13.1
// Buffer is the byte view: 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));
Output
50485001ff
roundtrip ok
00ab
ff

PHP v8.6.0

v8.6.0
// byte-level: every byte becomes two hex digits
$hex = bin2hex("PHP\x01\xff");
echo $hex, "\n";
echo bin2hex(hex2bin($hex)) === $hex ? "roundtrip ok\n" : "fail\n";
echo bin2hex("\x00\xab"), "\n"; // zero byte survives
// contrast with the numeric dechex: value formatting, no byte semantics
echo dechex(255), "\n";
Output
50485001ff
roundtrip ok
00ab
ff

Python v3.15.2

v3.15.2
# bytes.hex()/fromhex() are the byte-level pair
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())
# numeric contrast: hex() formats an integer (note the 0x prefix)
print(hex(255))
Output
50485001ff
roundtrip ok
00ab
0xff

Rust v1.99.1

v1.99.1
fn main() {
    // byte-level pair, hand-rolled: {:02x} per byte
    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);
    // numeric contrast: {:x} formats an integer
    println!("{:x}", 255u32);
}
Output
50485001ff
roundtrip ok
00ab
ff

TypeScript v26.13.1

v26.13.1
// Buffer is the byte view: toString('hex') / from(hex)
// latin1 keeps \xff as one byte (UTF-8 would expand it to 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));
Output
50485001ff
roundtrip ok
00ab
ff

Language differences

C: hand-rolled %02x encoding plus sscanf decoding (example); no standard hex codec, use OpenSSL or a maintained implementation in production.

C++: sstream with the hex manipulator (example); since C++17 std::from_chars (base 16) decodes back.

C#: Convert.ToHexString/FromHexString are the standard pair (.NET 5+, example); the output is uppercase by default — ToLowerInvariant to match PHP's shape.

Go: encoding/hex EncodeToString/DecodeString (example); the difference from fmt.Sprintf("%x") is exactly byte level vs numeric level.

Java: HexFormat (JDK 17+) is the standard pair (example); before 17 you hand-rolled or used Apache Commons Codec; byte is signed so (byte)0xFF needs the explicit narrowing.

JavaScript: Buffer.toString('hex')/Buffer.from(hex,'hex') (example); browsers have no Buffer — hand-write with Array.map(b => b.toString(16).padStart(2,'0')).

PHP: bin2hex/hex2bin are byte-level operations (two characters per byte, \x00 encodes as 00 and survives); hex2bin throws ValueError on odd-length input; the division of labor versus dechex/hexdec: bin2hex encodes byte sequences while dechex formats an integer value — "ff" can come from 255 or from \xff with completely different semantics.

Python: bytes.hex()/bytes.fromhex() are the standard pair (example); versus hex(): bytes.hex has no 0x prefix and works on byte sequences.

Rust: hand-rolled {:02x} encoding plus from_str_radix decoding (example); the hex crate is the production standard.

TypeScript: same Buffer pair as JavaScript (example); at the type layer Buffer comes from @types/node.