John Davidson

Converting binary string to hex in PHP

0 comments
Message:


I have a string of binary text which is a multiple of 8 characters long. Take the following for example.


$fullNameBin = "01010001000010110110010000010011000110000111100011001011111110110100111100111100";

I wish to convert this to hex. Note that the bits of each byte are in least significant to most significant order, so the above should result in


$fullNameCoded = "8AD026C8181ED3DFF23C";

In Perl, this can be achieved using


my $fullNameCoded = "";
for ( unpack( '(A8)*', $fullNameBin ) ) {
$fullNameCoded .= sprintf( "%02X", oct( "0b" . reverse( $_ ) ) );
}

or


my $fullNameCoded = uc unpack 'H*', pack 'b*', $fullNameBin;

PHP's pack/unpack is much more limited than Perl's, and a naive translation was unfruitful.


foreach ( unpack( "A8*", $fullNameBin) as $item ) {
$fullNameCoded .= sprintf( "%02X", octdec( "0b" . strrev( $item ) ) );
}


My Answer:
Unfortunately, PHP's pack/unpack functions do not have the same flexibility as Perl's when it comes to converting binary strings to hex. However, you can achieve the desired result by using a loop to process each 8-bit chunk of the binary string and convert it to hex manually.

Here's an example of how you can do this in PHP:

php
$fullNameBin = "01010001000010110110010000010011000110000111100011001011111110110100111100111100";
$fullNameCoded = "";

for ($i = 0; $i < strlen($fullNameBin); $i += 8) {
$byte = substr($fullNameBin, $i, 8);
$byte = strrev($byte); // Reverse the bits to get the correct order
$hex = dechex(bindec($byte)); // Convert binary to decimal, then decimal to hex
$fullNameCoded .= str_pad($hex, 2, "0", STR_PAD_LEFT); // Ensure 2 characters for each byte
}

echo strtoupper($fullNameCoded); // Output the result in uppercase


This code snippet will produce the same result as the Perl code you provided.

Rate this post

3 of 5 based on 6354 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us