0

The php manual says that hex2bin() returns a string with a binary representation.

I have this code:

$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);

The output is:

string 'example hex data' (length=16)

Pardon me if I'm wrong but I believe that the output isn't a binary string?? Did the manual made an error, or am I missing something?

-------------edit------------

Is 'example hex data' a binary representation of data?

Julian S
  • 361
  • 3
  • 13
  • 4
    http://php.net/manual/en/function.hex2bin.php: "Caution This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function. " – Frank Apr 15 '15 at 08:29
  • what you want hex to binary conversion? – Saty Apr 15 '15 at 08:35

2 Answers2

3

hex2bin turns hexadecimal numbers into raw bytes. These raw bytes output to the screen will be interpreted by your browser and/or CLI, which will turn it into text. bin2hex does not return a string like "01001000101" if that's what you expected; that'd be an ASCII representation of a binary string, not a binary string. See for example this if that's what you want: How to see binary representation of variable

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
2

From php manual:
"This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function."

"Decodes a hexadecimally encoded (binary) string" and "Returns the binary representation of the given data" (machine code ie. what's written to disk or processed by the computer hardware)

To answer your question:

Yes 'example hex data' is a (decoded) binary representation of (the given text) data.
The hex (encoded) representation of the same data is 6578616d706c65206865782064617461. To display the binary (base 2) equivalent of the above hex (base 16) number, you'd base_convert() it (to get a string of 0s & 1s; the ASCII codes/representation)

The confusion seems to arise between the results of hex2bin and base_convert().

As an example:

Some data on disk can be displayed (on console) as 'A'
bin2hex would return this (encoded) as '41' (hex representation).
base_convert() would return this (same) data as '01000001'
hex2bin would then decode this '41' to the machine (ASCII) code equivalent 'A' (the binary representation, which may be written to disk as binary data)

Zimba
  • 2,854
  • 18
  • 26