用PHP反转变量中的所有位 [英] Reversing all bits in a variable with PHP

查看:58
本文介绍了用PHP反转变量中的所有位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用PHP读取一个二进制文件,搜索一个位置,反转它们的位并处理结果.

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

当前我的代码如下:

$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.

您是否有一种有效的解决方案,可以逆转所有 PHP中的二进制变量中的位?

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

这是手动转换的样子:

推荐答案

最后,我设法使用以下算法反转了PHP中字节的位:

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);

首先,将字节转换为int并获取二进制表示形式.然后将其填充为0,直到长度为8个字符.然后它会反转字符串并将字符串组合回一个数字.最后一步是再次将其打包为一个字节的字符串.

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.

这篇关于用PHP反转变量中的所有位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆