Hexadecimal to binary

Views: 34 Last modified: August 03rd, 2011 Comments: 0

This function will return the binary value of a hexadecimal. If the input is not hexadecimal valid, it will return false. This function respects the 4 bits nibble rule so, for example, 1 will become 0001 etc. Please note that this function does not support big values like a hexadecimal larger then 14 characters. If you want support on bigger hexadecimals, use the second snippet, seen @ the php documentation. Credits for that guy.

<?php
// If the function hexbin isnt defined
if ( !( function_exists( 'hexbin' ) ) )
{
	// Define function
	function hexbin( $hex )
	{
		// Check characters for hexadecimal match
		$valid = preg_match( '@^[0-9a-f]+$@si', $hex );

		// Return false if the input is not hexadecimal
		if ( !$valid ) return false;

		// Binary
		$bin = decbin( hexdec( $hex ) );

        // Count characters from last nibble
        $last_nibble = end(str_split($bin, 4));

        // Count last nibble
        $count_last_nibble = strlen($last_nibble);

        // Complete result
        return ($count_last_nibble <= 4) ? str_repeat('0', (4-$count_last_nibble)).$bin : $bin;
	}
}

// Will echo 0100110010100101
echo hexbin( '4CA5' );
?>

This function supports bigger values!

<?php
function hexbin( $str_hex )
{
	$str_bin = FALSE;
	for ( $i = 0; $i < strlen( $str_hex ); $i++ )
	{
		$str_bin .= sprintf( "%04s", decbin( hexdec( $str_hex[$i] ) ) );
	}
	return $str_bin;
}
?>
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {2+7} =  
    Anything to add ?

        You must be logged in to post a comment.