dongzhi2014 2012-03-25 02:00
浏览 50
已采纳

在PHP(或任何语言)中,可以合并2个位掩码,同时保持orignal位的“身份”吗?

This may be a really silly question, but it just crossed my mind and I thought it would be interesting to know for sure....

So here is the scenario:

Users have 3 options for each day of the week: AM, PM, and OFF. These are mutually exclusive choices, so there is no option to work both an AM and PM on same day.

So if I wanted to store their AM shifts and PM shifts as separate bitmasks, and User1 chooses the following:

 S    M   T   W   Th   F   Sa
 A    P   X   A   X    P   A

I would have the following:

 $shifts['User1']['AM'] = 73;  //  1001001
 $shifts['User1']['PM'] = 34;  //  0100010

Now, if I just wanted to know which days User1 worked, I could obviously just do:

 $shifts['User1']['All'] = $shifts['User1']['AM'] | $shifts['User1']['PM'];

Or even just:

 $shifts['User1']['All'] = $shifts['User1']['AM'] + $shifts['User1']['PM'];

But what if I wanted the final result to distinguish AM from PM, something to the effect of:

 $shifts['User1']['AM'] = A00A00A;
 $shifts['User1']['PM'] = 0P000P0;

So that the A's and P's are both considered set, but that

 A00A00A | 0P000P0 = AP0A0PA;

Is there a common way of doing this, or am I thinking about this totally wrong?

  • 写回答

5条回答 默认 最新

  • doutian4046 2012-03-25 02:36
    关注

    To represent three states in a binary fashion you need 2 bits. For instance, you could say that:

    PM = 01

    AM = 10

    OFF = 00

    So now you have this:

    A00A00A translates to 10 00 00 10 00 00 10

    0P000P0 translates to 00 01 00 00 00 01 00

    Applying bitwise OR operation:

    10 00 00 10 00 00 10
    00 01 00 00 00 01 00
    --------------------
    10 01 00 10 00 01 10
    A  P  0  A  0  P  A
    

    You get AP0A0PA, your desired result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?