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 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢