← Back to Chapters

PHP bin2hex() & hex2bin()

? PHP bin2hex() & hex2bin()

? Quick Overview

The bin2hex() and hex2bin() functions in PHP are used for converting between binary and hexadecimal formats. These functions are especially useful for data manipulation, encoding, and cryptographic purposes.

⚡ Key Concepts

  • bin2hex() converts binary data into a readable hexadecimal string
  • hex2bin() converts hexadecimal data back into binary format
  • Commonly used in encryption, hashing, and secure data storage

? Syntax / Theory

  • bin2hex(string $binary): string
  • hex2bin(string $hex): string|false

? Example 1: Using bin2hex()

? View Code Example
// Convert a plain string into hexadecimal format
<?php
$string = "hello";
$hex = bin2hex($string);
echo $hex;
?>

?️ Output

68656c6c6f

? Example 2: Using hex2bin()

? View Code Example
// Decode hexadecimal data back into its original string
<?php
$hex = "68656c6c6f";
$binary = hex2bin($hex);
echo $binary;
?>

?️ Output

hello

? Interactive Flow (Conceptual)

Binary → Hex → Binary

This conversion process is reversible and ensures safe transport of binary data through text-based systems.

? Use Cases

  • Encoding binary data for storage in databases
  • Transmitting binary data via APIs
  • Cryptography and hashing workflows
  • File and image binary processing

✅ Tips & Best Practices

  • Always validate hexadecimal strings before using hex2bin()
  • Use these functions for safe binary-to-text conversions
  • Ideal for encoding sensitive or non-printable data

? Try It Yourself

  • Convert user input text to hex and back
  • Store binary data as hex in a database
  • Encode file contents using bin2hex() and restore them