Content · Programming · PHP

PHP bin2hex() Function: Usage and Examples

Learn how PHP bin2hex works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Converts bytes into their hexadecimal representation.

What Is bin2hex() in PHP?

Converts bytes into their hexadecimal representation.

Its syntax is:

bin2hex(string $string): string

Parameters:

  • $string — Accepted as string; required argument.

Return type: string. Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.

Availability: Available in standard PHP.

Example 1: Basic Usage

<?php

echo bin2hex("Hi");

Output:

4869

Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.

Example 2: A Different Input

<?php

echo bin2hex("A");

Output:

41

Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.

Practical Example: Applying It in a Program

<?php

$binaryToken = random_bytes(8);
$token = bin2hex($binaryToken);
echo strlen($token);

Output:

16

Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.

Important Behavior and Edge Cases

  • Key behavior: Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.
  • Environment: Available in standard PHP.

Comparison With Related Functions

FunctionPurpose
bin2hex()converts bytes into their hexadecimal representation.
hex2bin()hex2bin() converts a valid hex string to binary bytes; bin2hex() produces a hex string from bytes.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Each byte becomes two hexadecimal charactersEach byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.

Key Takeaways

  • converts bytes into their hexadecimal representation.
  • Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.
  • Available in standard PHP.

Summary: Each byte becomes two hexadecimal characters. The result is not encryption, and encoding does not hide sensitive data.

Share this resourceSend this page to someone who may find it useful.