PHP convert string to hex and hex to string

257,409

Solution 1

For people that end up here and are just looking for the hex representation of a (binary) string.

bin2hex("that's all you need");
# 74686174277320616c6c20796f75206e656564

hex2bin('74686174277320616c6c20796f75206e656564');
# that's all you need

Doc: bin2hex, hex2bin.

Solution 2

For any char with ord($char) < 16 you get a HEX back which is only 1 long. You forgot to add 0 padding.

This should solve it:

<?php
function strToHex($string){
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}
function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}


// Tests
header('Content-Type: text/plain');
function test($expected, $actual, $success) {
    if($expected !== $actual) {
        echo "Expected: '$expected'\n";
        echo "Actual:   '$actual'\n";
        echo "\n";
        $success = false;
    }
    return $success;
}

$success = true;
$success = test('00', strToHex(hexToStr('00')), $success);
$success = test('FF', strToHex(hexToStr('FF')), $success);
$success = test('000102FF', strToHex(hexToStr('000102FF')), $success);
$success = test('↕↑↔§P↔§P ♫§T↕§↕', hexToStr(strToHex('↕↑↔§P↔§P ♫§T↕§↕')), $success);

echo $success ? "Success" : "\nFailed";

Solution 3

PHP :

string to hex:

implode(unpack("H*", $string));

hex to string:

pack("H*", $hex);

Solution 4

Here's what I use:

function strhex($string) {
  $hexstr = unpack('H*', $string);
  return array_shift($hexstr);
}

Solution 5

function hexToStr($hex){
    // Remove spaces if the hex string has spaces
    $hex = str_replace(' ', '', $hex);
    return hex2bin($hex);
}
// Test it 
$hex    = "53 44 43 30 30 32 30 30 30 31 37 33";
echo hexToStr($hex); // SDC002000173

/**
 * Test Hex To string with PHP UNIT
 * @param  string $value
 * @return 
 */
public function testHexToString()
{
    $string = 'SDC002000173';
    $hex    = "53 44 43 30 30 32 30 30 30 31 37 33";
    $result = hexToStr($hex);

    $this->assertEquals($result,$string);
}
Share:
257,409
JoeNguyen
Author by

JoeNguyen

Magento Tech Lead Technical Trainer

Updated on July 08, 2022

Comments

  • JoeNguyen
    JoeNguyen almost 2 years

    I got the problem when convert between this 2 type in PHP. This is the code I searched in google

    function strToHex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= dechex(ord($string[$i]));
        }
        return $hex;
    }
    
    
    function hexToStr($hex){
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2){
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }
    

    I check it and found out this when I use XOR to encrypt.

    I have the string "this is the test", after XOR with a key, I have the result in string ↕↑↔§P↔§P ♫§T↕§↕. After that, I tried to convert it to hex by function strToHex() and I got these 12181d15501d15500e15541215712. Then, I tested with the function hexToStr() and I have ↕↑↔§P↔§P♫§T↕§q. So, what should I do to solve this problem? Why does it wrong when I convert this 2 style value?

    • जलजनक
      जलजनक about 11 years
      You know there are hex2bin() and bin2hex() in PHP?
    • Déjà vu
      Déjà vu about 11 years
      strToHex returns a string of hex - so if you XOR that directly with the ^ operator, that won't give any good result. Maybe you could give strToHex another param being the number you want to XOR with, and XOR directly inside that function: $hex .= dechex(ord($string[$i]) ^ $MYKEYBYTE);
    • JoeNguyen
      JoeNguyen about 11 years
      I thought that the problem is at hexToStr() function. Because when it convert to string, it pass the space or some special character, and make the problem
    • JoeNguyen
      JoeNguyen about 11 years
      I tried hex2bin() and bin2hex(). It's really good and solve this. but in real situation, It doesn't. It just be right if I call bin2hex() function after encrypt by XOR the plaintext with key. But in a real situation, we usually use strToHex() after XOR , so when we decrypt by XOR the Crypt with KEY to get the plaintext, we call the hexToStr() It will get wrong result.
  • tropicalm
    tropicalm over 10 years
    In the strToHex function, as an alternative to the whole dechex() and substr -2, one may just use: $hex .= sprintf('%02.x', $ord);
  • Geoffrey
    Geoffrey almost 5 years
    You could avoid the call to implode by using list, ie: list(, $hex) = unpack('H*', $string);
  • Moeez
    Moeez about 4 years
    In case of 16 bit what should I do?
  • Moeez
    Moeez about 4 years
    The HEX value of 64 is 40. But it's returning me something else
  • PeterT
    PeterT almost 4 years
    Why not convert the accented characters first
  • ner0
    ner0 almost 4 years
    Any particular approach recommended? mb_convert_encoding? This is outside the original scope, but the hex information will be converted back into string in MSSQL, which doesn't have a decoding function.
  • Moeez
    Moeez almost 4 years
  • Moeez
    Moeez almost 4 years
    what about 2's compliment?