Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

php - Working with bitcode

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Bitwise ANDs:

$input = 13;

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

edit

You can avoid the ifs with something like:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...