User Contributed Notes 22 notes

This function is for converting binary data into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal. If you want that functionality, you can simply do this:

<?php$binary = "11111001";$hex = dechex(bindec($binary));echo $hex;?>

This would output "f9". Just remember that there is a very big difference between binary data and a string representation of binary.

In response to Patrik:A simpler way to print a number in binary is to use base_convert().<? echo base_convert($bin, 10, 2); ?>If you need it to print all 32 bits (as your function does) you can just pad it out:<? echo str_pad(base_convert($bin, 10, 2), 32, '0', STR_PAD_LEFT); ?>The conversion is from base 10 because when $bin is passed to base_convert(), it is converted to a string, and the default representation is in decimal.Hope this helps.

modified version of Thoth's hexbin and binhex to convert any size numbers (original doesn't take more than integer - 32bit)<?function hexbin($hex){$bin=''; for($i=0;$i<strlen($hex);$i++)$bin.=str_pad(decbin(hexdec($hex{$i})),4,'0',STR_PAD_LEFT); return $bin;}

Here's a modified version of an earlier post (asc2bin and bin2asc) to convert an incoming ascii string to hex and out again. For example, this is really useful if you want to insert data into a mySQL database which contains both escaped and non-escaped characters. For example, if you want to store code snibbets in a mySQL text field:

printf("here's some \"text\".");

If you INSERT this into mySQL, it probably won't come out in friendly executable format, and you can't escape all double-quotes, nor can you strip out all the slashes. One solution is to just convert the string to hex, store it in hex, then convert back to ascii before using it in some way: