Dev Corner

Software Developer’s Notepad

PHP implements a bin2hex function that converts given binary string to hexadecimal string. Sometimes you need to solve the reverse task. You are given hexadecimal string and you need a PHP function that converts it to a binary string.

The following PHP function converts a hexadecimal string to a binary string. The function is byte-based which means that it interprets consecutive pairs of hexadecimal digits and converts them to binary characters using the standard PHP function chr(). White-spaces are skipped.

A good extension point would be to implement word-based function that works in Big-Endian and Little-Endian modes.

<?php
 
define('HEX2BIN_WS', " \t\n\r");
 
function hex2bin($hex_string) {
    $pos = 0;
	$result = '';
	while ($pos < strlen($hex_string)) {
	  if (strpos(HEX2BIN_WS, $hex_string{$pos}) !== FALSE) {
	    $pos++;
	  } else {
	    $code = hexdec(substr($hex_string, $pos, 2));
		$pos = $pos + 2;
	    $result .= chr($code); 
	  }
	}
	return $result;
}
 
?>

Back to: PHP Tips and Recipes

Add A Comment

You must be logged in to post a comment.