How to Get a Hex Dump of a String in PHP

How can I get a hex dump of a string in PHP?

echo bin2hex($string);

or:

for ($i = 0; $i < strlen($string); $i++) {
echo str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT);
}

$string is the variable which contains input.

How to add up hex string and perform NOT-operation on it?

 $hex_array = str_split($hex, 2);
foreach ($hex_array as $byte) {
$sum += hexdec($byte);
}

echo "Sum: ", $sum, "\n";
echo dechex($sum);

EDIT

Explanation:
Assuming the input string has even number of characters we can start from the first byte and take two hex characters (representing one byte). That's what str_split does. Then we loop over each of that two-character substrings and parse them to number using dechex that we then add to the main sum. After that the only thing left is to represent that sum as hex number, using hexdec.

References from php.net:

  • array str_split ( string $string [, int $split_length = 1 ] )
  • string dechex ( int $number )
  • number hexdec ( string $hex_string )

What is the correct code to convert to hex in below format?

The hex dump that you are getting is UTF-8 format, which is a way to represent Unicode characters reliably in a 8-bit stream.

E0 A6 AC E0 A6 BE E0 A6 82 E0 A6 B2 E0 A6 BE E0 A6 A6 E0 A7 87 E0 A6 B6

The example on the other hand is a dump of the UTF-16 (or truncated 16-bit Unicode codepoint) values:

09AC 09BE 0982 09B2 09BE 09A6 09C7 09B6

In your case the solution is to convert to UTF-16 encoding:

echo bin2hex(mb_convert_encoding('বাংলাদেশ', 'UTF-16'));"
> 09ac09be098209b209be09a609c709b6

Note that using Unicode characters in code is unreliable, because the interpretation of the bytes in a string will depend on your system details / editor / compiler or interpreter settings etc.

Writing Hex data to a file

If you want to write the byte 0x0f to the file, simply write the character with that ASCII code. You effectively want to undo ord, and the reverse function is chr:

<?php
$tmp = ord('F'); //gives the decimal value of character F (equals 70)
$tmp = $tmp - 55; //gives 15 - decimal equivalent of 0x0F
$tmp = chr($tmp); // converts 15 to a character
$fp = fopen("testing.data","wb+");
fwrite($fp,$tmp);
fclose($fp);
?>

How can a var_dump return me : string(160)

I'm guessing you have only produced XML, without character data, e.g.:

var_dump('<something/>');

Try instead:

var_dump(htmlentities('<something/>'));

or, better yet, if you know the character set:

var_dump(htmlentities('<something/>', ENT_NOQUOTES, 'UTF-8'));

How do I get the byte values of a string in PHP?

Use the ord function

http://ca.php.net/ord

eg.

<?php
$var = "nÖ§9q1Fª£ˆæÓ§Œ_»—Ló]j";

for($i = 0; $i < strlen($var); $i++)
{
echo ord($var[$i])."<br/>";
}
?>


Related Topics



Leave a reply



Submit