Php hex to bytes

PHP Hex and Binary

Basically, this traverses the string and separates every 2 characters as hex rep per byte and convert them to binary string. I could successfully extract and convert text files to binary files with the following code: But when I run this function on a pdf file or other binary file, it is corrupted.

PHP Hex and Binary

I have a string in the following format: «0A1344010400010005» (hex representation)

I would need to convert this string into an array of bytes (0x0a, 0x13, 0x44, and so forth) so that these data can be used in the following function:

$data = $this->data; for ($i = 0; $i < sizeof($data); $i++) < // 1.value right shift 8 digits (equal to divide 256) // 2.XOR value and incoming data, then AND 0xFF // 3. get an index£¨then search related index data in CRC16_TABLE // XOR again $this->value = ($this->value >> 8) ^ $this->arr[($this->value ^ $data[$i]) & 0xff]; > 

$this->value value is 0xFFFF . $this->arr is an array containing elements: array(0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf) .

I have done the following. Basically, this traverses the string and separates every 2 characters as hex rep per byte and convert them to binary string .

$data = array(); $len = strlen($str); if($len % 2 == 1) $str = "0".$str; $len = strlen($str); for($i =0; $i < $len; $i=$i+2) < $data[] = hex2bin(substr($str,$i,2)); >$this->data = $data; 

It seems that it is generating result of value 0 all the time. Is there anything that I should have done?

Читайте также:  Абсолютный адрес

Thank you so much for the help!

pack can convert a hex string into a binary string (bytes 0x0a, 0x13, 0x44, and so forth):

$data = pack('H*', '0A1344010400010005'); 

After that, what you have done should work, with one minor change: $data[$i] is actually a string and to get the value of the corresponding byte you need ord :

for ($i = 0; $i < strlen($data); $i++) < $this->value = ($this->value >> 8) ^ $this->arr[($this->value ^ ord($data[$i])) & 0xFF]; > 

hex2bin returns a binary string, you want an integer I think. Use ord to convert the characters to int

$data = array(); $len = strlen($str); if($len % 2 == 1) $str = "0".$str; $len = strlen($str); for($i =0; $i < $len; $i=$i+2) < $data[] = ord(hex2bin(substr($str,$i,2))); >$this->data = $data; 

Convert string to binary then back again using PHP, Your hash is already binary and ready to be used with your database. However you must need to convert it into a format the database column …

How to convert hexadecimal representation of data to binary data in PHP?

I’m familiar with php’s function bin2hex() for converting binary data to its hexadecimal representation.

However, what is the complement function to convert the hexadecimal representation of the data back to binary data?

$foo = "hello"; $foo = bin2hex($foo); echo $foo; // Displays 68656c6c6f 

How do I turn it back to «hello»?

$foo = "68656c6c6f"; // Now what? 

There is no hex2bin() function.

If you look at PHP’s bin2hex page, there’s suggested solutions including this one:

There’s also various implementations of hex2bin that you can choose from.

For those who have PHP 5.4 and above, there’s a standard way of doing this:

The output of the code above should be similar to:

string(16) «example hex data»

Php — How to do hex2bin in php5.3, hex2bin() function is supported after php5.4. It is not available in php5.3. How can I do hex2bin in php3 ? echo …

Convert 64 character hex String to BINARY(32)

I have an input in the form of «e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855″( 64 hexadecimal characters obtained from SHA-256) which I want to store in a database with MySqli. The column the value should be inserted to is of type BINARY(32). I think that the value is interpreted as a string, rather than a hex number, so MySQL returns «Data too long for column x at row y». How can I convert this string to 32 bytes in PHP? I already tried adding «0x» as a prefix, MySql’s CONVERT function and I read about hex2bin and bin2hex, which don’t seem to do what I want, and i tried both string and int types in bind_params (int results in 0x3000. regardless of the input)

Okay, Joni’s comment is the answer, i thought about hex2bin just as a way to make hex-encoded string readable, and i didn’t realize it compresses the hex value to a string which is short enough to be stored as binary. Thanks to joni and tkausl for enduring my incompetence in php and in managing stackoverflow questions 🙂

EDIT: i can’t close the question since the answer was posted as a comment, sorry for that.

PHP Binary to Hex with leading zeros, Browse other questions tagged php binary hex or ask your own question. The Overflow Blog Skills that pay the bills for software developers (Ep. 460)

Converting hex string to binary file makes it corrupt and unable to open

When converting the hexadecimal value, a pdf file , the file is corrupted.
This is the partial hex content of a simple pdf file I want to convert:

0x255044462D312E370D0A25B5B5B5B50D0A312030206F626A0D0A3C3C2F547970652F436174 

Full string: jsfiddle, pastebin

This question is a continuation of this question, where I said that I have to do a data migration between two programs that handle files differently. The source program stores the files hex encoded in the database.

I could successfully extract and convert text files to binary file s with the following code:

file_put_contents( 'document.pdf', hex2bin(str_replace('0x', '', $hexPdfString)) ); 

But when I run this function on a pdf file or other binary file, it is corrupted.
My question is pretty much the same as this one but discussion over there was unfortunately discontinued.

The result of hex decoding your string is corrupted because your string is incomplete , it only contains the first 65535 characters. After hex decoding one can see that the PDF is cut off inside a metadata stream:

20 0 obj > stream   Microsoft® Word 2019 Samuel Gfeller Microsoft® Word 20192021-06-17T13:00:19+02:002021-06-17T13:00:19+02:00 uuid:C29344F5-3E78-414A-B4E3-775A853B1A0Cuuid:C29344F5-3E78-414A-B4E3-775A853B1A0C 

The length 65535 of course is special, it’s 0xFFFF. Apparently some mechanism you used in retrieving that string could not handle strings longer than 65535 characters. Thus, you have to investigate the source of that string.

Considering the question you consider this question a continuation of, I’d assume that either the field in the MS SQL database you retrieve the data from is limited to 65535 bytes or your database value retrieval code cuts it down.

In the former case there’d be nothing you can do, the database contents simply would be incomplete. In the latter case you’d simply have to enable your database access code to handle long strings.

Php — Convert bytes to binary, Browse other questions tagged php random binary byte or ask your own question. The Overflow Blog Exploring the interesting and strange results …

Источник

hex2bin

This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

Parameters

Hexadecimal representation of data.

Return Values

Returns the binary representation of the given data or false on failure.

Errors/Exceptions

If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.

Examples

Example #1 hex2bin() example

The above example will output something similar to:

string(16) "example hex data"

See Also

  • bin2hex() — Convert binary data into hexadecimal representation
  • unpack() — Unpack data from binary string

User Contributed Notes 13 notes

The function hex2bin does not exist in PHP5.
You can use ‘pack’ instead :

$binary_string = pack(«H*» , $hex_string);

if you want to convert a hex encoded string to a binary string without any notices/errors regardless of the input, use this function:

function hex2binary ( $str )
return ctype_xdigit ( strlen ( $str ) % 2 ? «» : $str ) ? hex2bin ( $str ) : false ;
>

hex2binary ( «» ); // false
hex2binary ( «a» ); // false
hex2binary ( «ab» ); // binary-string

?>

if the return type is string, you have your binary-string. otherwise (bool) false.

I modified the function by Johnson a bit so it can be used as a drop-in-replacement. You don’t need to worry about upgrading php because when it is upgraded, it will use the build in function.

if ( ! function_exists ( ‘hex2bin’ ) ) function hex2bin ( $str ) $sbin = «» ;
$len = strlen ( $str );
for ( $i = 0 ; $i < $len ; $i += 2 ) $sbin .= pack ( "H*" , substr ( $str , $i , 2 ) );
>

The function pack(«H*» , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

#error:
hex2bin(): Hexadecimal input string must have an even length

For those who are facing the error above trying to convert hex to bin. you can pad your hex string with initial 0 before hex2bin.

function hexPad(string $hex_string)
$st_l = strlen($hex_string);
return str_pad($hex_string, $st_l + ($st_l % 2), ‘0’, STR_PAD_LEFT);
>

for usage hex2bin(hexPad(‘1bc’));

If you want to convert hex to GUID format (In my case, it was to convert GUID from MSSQL database) :

function hex2Guid ( $hex )
$hex = [
substr ( $hex , 0 , 8 ),
substr ( $hex , 8 , 4 ),
substr ( $hex , 12 , 4 ),
substr ( $hex , 16 , 4 ),
substr ( $hex , 20 ),
];

$order [ 0 ] = [ 6 , 7 , 4 , 5 , 2 , 3 , 0 , 1 ];
$order [ 1 ] = [ 2 , 3 , 0 , 1 ];
$order [ 2 ] = [ 2 , 3 , 0 , 1 ];
$order [ 3 ] = [ 0 , 1 , 2 , 3 ];
$order [ 4 ] = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ];

return strtoupper ( $result );
>

Example :
echo hex2Guid ( «64d3938b7008cd4bad5ffe56755d163f» );

Case of an incomplete hex string following function may help:
function make2validhex ( $data ) $data = (string) $data ;
$len = strlen ( $data );
if( $len % 2 ) return substr ( $data , 0 , $len — 1 );
>
return $data ;
>
?>
test:
$string = «not complete» ;
echo $string ;
echo PHP_EOL ;
$hex = bin2hex ( $string ); //»6e6f7420636f6d706c657465″
echo $hex ;
echo PHP_EOL ;
$deff = substr ( $hex , 0 , strlen ( $hex ) — 1 ); //»6e6f7420636f6d706c65746″
echo $deff ;
echo PHP_EOL ;
echo hex2bin ( make2validhex ( $deff )); //»not complet»
echo PHP_EOL ;
?>

For those who have php version prior to 5.4, i have a solution to convert hex to binary. It works for me in an encryption and decryption application.

function hextobin ( $hexstr )
<
$n = strlen ( $hexstr );
$sbin = «» ;
$i = 0 ;
while( $i < $n )
<
$a = substr ( $hexstr , $i , 2 );
$c = pack ( «H*» , $a );
if ( $i == 0 ) < $sbin = $c ;>
else < $sbin .= $c ;>
$i += 2 ;
>
return $sbin ;
>
?>

A drop-in hex2bin emulator which behaves just like the the one in v5.5.1.

if (! function_exists ( ‘hex2bin’ )) function hex2bin ( $data ) static $old ;
if ( $old === null ) $old = version_compare ( PHP_VERSION , ‘5.2’ , ‘ >
$isobj = false ;
if ( is_scalar ( $data ) || (( $isobj = is_object ( $data )) && method_exists ( $data , ‘__toString’ ))) if ( $isobj && $old ) ob_start ();
echo $data ;
$data = ob_get_clean ();
>
else $data = (string) $data ;
>
>
else trigger_error ( __FUNCTION__ . ‘() expects parameter 1 to be string, ‘ . gettype ( $data ) . ‘ given’ , E_USER_WARNING );
return; //null in this case
>
$len = strlen ( $data );
if ( $len % 2 ) trigger_error ( __FUNCTION__ . ‘(): Hexadecimal input string must have an even length’ , E_USER_WARNING );
return false ;
>
if ( strspn ( $data , ‘0123456789abcdefABCDEF’ ) != $len ) trigger_error ( __FUNCTION__ . ‘(): Input string must be hexadecimal string’ , E_USER_WARNING );
return false ;
>
return pack ( ‘H*’ , $data );
>
>
?>

$test = bin2hex(‘sample . ‘);
echo _hex2bin($test);

// another hex2bin replacement
function _hex2bin($result) $out = »;
for($c=0;$c > //end for
return (string) $out;
>

A way to convert hex strings in the form «0x123ABC» to integer is to use the function base_convert(«0x123ABC», 16, 10)

function Hex2Bin($data) $BinData = «»;
for ($i=0;$i $BinData .= chr( HexDec( substr($data,$i,2) ) );
return $BinData;

Источник

Оцените статью