Sling Academy
Home/PHP/PHP: Convert a string to binary and vice versa

PHP: Convert a string to binary and vice versa

Last updated: January 10, 2024

Introduction

Converting strings to binary and binary to strings is a common programming task in PHP. This tutorial covers various methods and functions in PHP to perform these conversions, enhancing your data processing skills.

String to Binary Conversion

To convert a string to its binary equivalent in PHP, you can use the built-in ord() and decbin() functions. These functions convert characters to their ASCII values and then into binary.

$string = 'Hello World';
$binary = '';
for ($i = 0; $i < strlen($string); $i++) {
    $binary .= sprintf('%08b', ord($string[$i])) . ' ';
}
echo $binary;

Output: 01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100

Binary to String Conversion

To convert binary to a string in PHP, we use the bindec() and chr() functions. Here’s an example:

$binary = '01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100';
$string = '';
foreach (explode(' ', $binary) as $bin) {
    $string .= chr(bindec($bin));
}
echo $string;

Output: Hello World

Using pack() and unpack()

The pack() and unpack() functions offer another way to convert between binary and strings. They are especially useful when dealing with data that has to conform to a specific binary format.

// String to binary using pack()
$string = 'Hello';
$binary = implode(' ', unpack('H*', $string));
$binary = binhex($binary);
echo $binary;

// Binary to string using unpack()
$binary = '48656c6c6f';
$string = pack('H*', $binary);
echo $string;

Here we are converting the hexadecimal back and forth, as directly dealing with binary can be unwieldy in PHP.

Advanced Binary Manipulations

In more complex scenarios, you might need to handle binary data with certain constraints or in combination with bitwise operations. PHP offers a suite of bitwise operators such as &, |, ^, and ~, which can operate on binary data.

$string = 'A';
$binary = decbin(ord($string));
// Invert bits
$inverted = ~bindec($binary);
// Convert back to string
$invertedString = chr(bindec($inverted));
echo $invertedString;

This example showcases simple bitwise manipulation, which could be the foundation for encryption/decryption techniques.

Handling Binary Data with fopen() and fread()

Beyond simple strings, PHP can read and write binary files with functions like fopen() and fread(). Let’s see how you can read binary data from a file:

$filename = 'example.bin';
$handle = fopen($filename, 'rb');
$contents = fread($handle, filesize($filename));
$binaryData = binhex($contents);
fclose($handle);
echo $binaryData;

This code chunk opens a file in binary mode and reads its contents as binary data.

Conclusion

This tutorial has explored different methods for converting strings to binary and back in PHP. We’ve seen basic conversions, handy functions like pack() and unpack(), advanced manipulation with bitwise operators, and handling binary files. Knowing these techniques is crucial for data encoding, cryptography, and efficient binary data processing.

Next Article: PHP: Convert a string to bytes and vice versa

Previous Article: PHP: Convert a string to hex and vice versa

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array