doz22551 2019-04-12 10:29
浏览 98
已采纳

如何根据动态值移动二进制字符串 - PHP

I have a binary string of 336 in 0 and 1 form. I am getting a value from a variable. Let's say the string is 010101010001111 and variable value is 3, then I want a string like this: 111010101010001.

Is it possible? How can it be done in PHP?

Any help would be highly appreciated.

  • 写回答

2条回答 默认 最新

  • dongmuyan5638 2019-04-12 12:01
    关注

    You have to do a bit of bit manipulation here,

    $string = '010101010001111';
    $decVal = bindec($string);
    $variable = 3;
    $result = decbin(($decVal >> $variable) | (($decVal << (strlen($string) - $variable)) & ~(~0 << strlen($string))));
    echo $result;
    

    Live Demo: https://3v4l.org/lSCLq

    The overall idea is like this:

    1. Convert binary string to decimal value.

      $decVal = bindec($string); // 010101010001111 --> 10895
      
    2. Right shift $decVal value by $variable positions.

      $decVal >> $variable  // 010101010001111 --> 000010101010001
      
    3. Left shift $decVal value by strlen($string) - $variable positions

      $decVal << (strlen($string) - $variable) // 010101010001111 --> 010101010001111000000000000
      
    4. AND the output of step# 3 with ...0000000000111111111111111

      (($decVal << (strlen($string) - $variable)) & ~(~0 << strlen($string))) // 010101010001111000000000000 & ...0000000000111111111111111 --> ...0000000000111000000000000
      
    5. OR the output of step# 2 and step# 4 to achieve the desired result

      ($decVal >> $variable) | (($decVal << (strlen($string) - $variable)) & ~(($decVal | ~0) << strlen($string))) // 000010101010001 | ...0000000000111000000000000--> 111010101010001
      
    6. Finally, display the output of step# 5 in binary string representation.

      $result = decbin(...);
      echo $result;
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私