Jump to content

Recommended Posts

I'm going through a loop and using an AND check to see if an appropriate flag has been set, and if so increase the appropriate hour by 1. Code is (without all the SQL getting the data):

<?php
while($row = $result->fetch_row()) {
for($j = 0; $j < $bat->length; $j++) {
 $bwt = $bitwise_array[$j];
 if(($row[0] & $bwt) == $bwt)
  $hours[$j]++;
}
}

Right now bitwise array is just a manually populated array with 1,2,4,8,16 etc... However is there a mathematical function for calculating the proper bit in decimal?

So in binary the first bit = 1, the second bit = 2, the third bit = 4, the fourth = 8 and so on. I have manually filled in an array for that. If I specify the bit, is there a function that will give me the decimal value of that bit. I always thought it was 2n, but that does't work.

It still isn't completely clear, but if you have the binary string '01000', you can use bindec to get the decimal value. If that isn't what you mean, post an example of the actual data, and the expected output.

OK, in the code above the function goes from 0 up to an unknown number (max of 11). Each loop through it tests the result row[0] for the next bit to see if it is set. So first loop through it is


if(($row[0] & 1) == 1)
$hours[$j]++;

 

Second loop through it's

 

if(($row[0] & 2) == 2)
$hours[$j]++;

 

Third...

if(($row[0] & 4) == 4)
$hours[$j]++;

 

If you see my OP that number is a variable, $bwt. That is determined by a manually filled in array right now. However what I want is a mathematical function to get that number for me, so I can put in the bit, and get the decimal value for it: i.e.

Bit = Decimal

1 = 1

2 = 2

3 = 4

4 = 8

5 = 16

6 = 32

7 = 64

8 = 128

and so on.

Edited by Vel

Note you can just use the bitshift operators too.

 

echo (1<<0) . PHP_EOL; //1
echo (1<<1) . PHP_EOL; //2
echo (1<<2) . PHP_EOL; //4
echo (1<<3) . PHP_EOL; //8
echo (1<<4) . PHP_EOL; //16
//...

 

The expression y<<x moves the bits in y x places to the left.  When y is 1 (pattern 00000001) then you're just moving the one bit x place.  eg 1<<5 would be (00100000)

  • 3 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.