Page 1 of 1

heeelp, using & and binary schemes

Posted: Sat Apr 15, 2006 3:09 pm
by R4000
Hey guys, im stuck again xD... mainly with an area of PHP i never explored or wanted to :P
Basicly it involves the '&' and '^' maths thingys.
correct me if im wrong, but i belive ^ is the same as 'to the power of' (e.g. 2^4 = 2*2*2*2)
Yes?

If so, im happy with that :P

The only thing i cant get my head around is: the & thingy, ive seen it used like:

Code: Select all

echo 32 & 128;
but i have NO IDEA what the hell this does!.


My final question is, i want to use a 'binary scheme' like:

Code: Select all

$perms = array(
'candelete' => 1,
'canedit' => 2
'canadd' => 4,
'canview' => 8,
'canbackup' => 16,
'acp_access' => 32,
'donated' => 64,
'fancystars' => 128,
ect.
);
so i could do:
4+8+64 = 76 (can add, can view, and has donated.)
now i have that number (76) in the database col 'perms'.
how do i turn that 76 BACK into 4+8+64? i know lots of software that does it... ive always wanted to be able to do it, but never researched it xD heeelp :P

Posted: Sat Apr 15, 2006 3:13 pm
by feyd
^ in computer languages generally is a bitwise XOR operator, although in typical (basic) math notation, ^ is powers yes.

Anyways, search my posts for "bitwise".

Posted: Sat Apr 15, 2006 4:58 pm
by R4000
Kk, thanks for the bitwise stuff ill look closer at that, but from what ive seen about it. it doesnt answer my last question. any ideas howto do that? (i know i can be done)

EDIT: scrap that... they are going to be used now i read about it xD

anyway, what i plan to do, is have a chess like game... and the user selects 5 pieces before the game starts.

pieces:

Code: Select all

$pieces = array(
'elf' => 1,
'goblin' => 2,
'necro' => 4,
'dwarf' => 8,
'mage' => 16,
'lightningb' => 32,
ect.
);
but from what i see, i need something like:

Code: Select all

$user_has = 31; // elf, goblin, dwarf, necro, mage
if($user_has & 4){ // if user has necro.
}
// same for EVERY piece.
thats gonna be a bit long for the 300 pieces ill have.
couldn't i just have something like:

Code: Select all

$pieces = array(
'elf' => 1,
'goblin' => 2,
'necro' => 4,
'dwarf' => 8,
'mage' => 16,
'lightningb' => 32,
);
$pieces = array();
$user_has = 31; // elf, goblin, dwarf, necro, mage
foreach ($pieces as $key=>$val){
 if($user_has & $val) $pieces[] = $key;
}
EDIT: dont u just love it when you type something long and winded, asking if its correct and santax is right. then it WORKS! OMG IT WORKS xD :P.. yay now ive got tons of coding to do :P