0

I have a database with a field containing a bit mask, and I have a hex bit mask list which looks like this:

2^8 256 = Type 1
2^9 512 = Type 2
2^0 001 = Type 3
2^4 016 = Type 4
2^1 002 = Type 5
2^5 032 = Type 6

I'm trying to "decode" (not sure of the right term)
with php what the bit mask was, for example: 003

How would I know that 003 was a combination of 002 & 001?

Please, I dont know anything about this, help shed some light.
I need to be able to do it with php.

Tony
  • 121
  • 2
  • 13
  • `if ($mask & 1) { echo 'bit 1 is set'; } if ($mask & 2) { echo 'bit 2 is set'; } if ($mask & 4) { echo 'bit 3 is set'; } if ($mask & 8) { echo 'bit 4 is set'; }` etc – Mark Baker Mar 14 '15 at 19:34

1 Answers1

0

First, you should define constants for your values:

const TYPE1 = 0b01000000;
const TYPE2 = 0b10000000;
const TYPE3 = 0b00000001;
const TYPE4 = 0b00010000;
const TYPE5 = 0b00000010;
const TYPE6 = 0b00100000;

This will keep you sane. I used binary (0b notation), but you could use hex (0x) or decimal just as easily; I think binary makes it easiest to see which bit represents which constant though, and when you're defining new constants you can easily see which bits have already been used. Bear in mind that constants' names are case-sensitive... but just stick with ALL_CAPS constants and you'll save yourself a lot of headache down the road.

Then you can use the logical operator & to test for each one, as per the comment by @MarkBaker :

if ($mask & TYPE1) echo "Type 1 is set\n";
if ($mask & TYPE2) echo "Type 2 is set\n";
if ($mask & TYPE3) echo "Type 3 is set\n";
if ($mask & TYPE4) echo "Type 4 is set\n";
if ($mask & TYPE5) echo "Type 5 is set\n";
if ($mask & TYPE6) echo "Type 6 is set\n";

For your example of the value 3, you'd get an output of:

Type 3 is set
Type 5 is set

Also, a caveat when working in PHP (and many other languages) -- numbers written with a leading zero, e.g. 032 in your question, are interpreted as octal! Therefore 032 is not actually 32, but rather 26!

Doktor J
  • 1,058
  • 1
  • 14
  • 33