denoise denoise - 2 months ago 15
PHP Question

Reversing all bits in a variable with PHP

I need to read a binary file in PHP, search for a location, reverse their bits and manipulate the result.

currently my code looks like this:

$src_file = "firmware/shapeshifter_v2.02.jic";
$offset = 983195;

if ($src_handle = fopen($src_file,"rb")) {
fseek($src_handle, $offset);
$src_content = fread($src_handle, 1024);
fclose($src_handle);

$src_content = $src_content & 128 >> 7 + $src_content & 64 >> 5 + $src_content & 32 >> 3 + $src_content & 16 >> 1 + $src_content & 8 << 1 + $src_content & 4 << 3 + $src_content & 2 << 5 + $src_content & 1 << 7;

print bin2hex($src_content);
}


I'm trying to reverse the all the bits from the chunk with an algorythm found in this forum, but I cannot reverse more than one bit with it.

Do you have an efficient solution to reverse all the bits in a binary variable in PHP?

this is how it looks like with a manual conversion:

enter image description here

Answer Source

finally I managed to reverse the bits of a byte in PHP using the following algorithm:

$binary = decbin(ord($char));
$binary = str_pad($binary, 8, 0, STR_PAD_LEFT);
$binary = strrev($binary);
$reversednumber = bindec($binary);
$reversed = pack("C",$reversednumber);

first, convert the byte to an int and get the binary representation. Then it fills it with 0 until it's 8 chars long. then it reverses the string and assemble the string back to a number. The final step is to pack it as an one byte string again.