使用位码 [英] Working with bitcode

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

问题描述

对于SO来说这有点麻烦,因为我不是在试图解决特定的问题,而是只是为了了解如何实现某些问题.但是我追求代码,所以让我们看看它如何运行...

This is slightly OT for SO, because I'm not trying to solve a specific problem, instead just to understand how something might be implemented. But I am after code, so let's see how it goes...

假设我们在一周中的每一天都有一个复选框,并且我们决定将这些复选框的任何组合存储为单个数字,例如:

Let's say we had a checkbox for each day of the week, and we decided to store any combination of those checkboxes as a single number, such that:

  0 = no days
  1 = Monday 
  2 = Tuesday
  4 = Wednesday
  8 = Thursday
 16 = Friday
 32 = Saturday
 64 = Sunday
127 = everyday

如何在PHP中实现该逻辑,以便如果我提交说"13",PHP将只在星期一,星期三和星期四复选框中打勾?

How might one go about implementing that logic in PHP so that if I submitted say, "13", PHP would know to tick only the Monday, Wednesday and Thursday checkboxes?

推荐答案

按位AND s:

$input = 13;

if( $input & 1 ) {
  echo 'Monday';
}
if( $input & 2 ) {
  echo 'Tuesday';
}
if( $input & 4 ) {
  echo 'Wednesday';
}
// etc

编辑

您可以通过以下方式避免使用if:

$input = 13;

$days = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');

for( $i=0; $i<7; $i++ ) {
    $daybit = pow(2,$i);
    if( $input & $daybit ) {
        echo $days[$i] . ' ';
    }
}

//output: mon wed thu

除了给这只猫皮上皮以外,还有两种以上的方法,但是最佳"方法取决于您的结果/输出需要什么.

There's more than these two ways to skin this particular cat, but the 'best' way depends on what your result/output needs to be.

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

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