PDA

View Full Version : computing bitflags



subhailc
Apr 1st, 2006, 10:45 AM
ive bumped into an abstraction i cant get my head around - parsing a bitflag. the most common example i can think of is ftp permission
4-read
2-write
1-execute
adding them generates a true or false to each
7=1,1,1
1=1,0,0
3=1,1,0
i presume there's a relatively automatic behaviour using bitwise shifting, or perhaps even modulo? i've had limited success using variations on
flag&=flag-1;but as i said i'm stuck. any guidance would be useful and appreciated, tyia.

dumpfi
Apr 1st, 2006, 11:20 AM
Well, if you want to use bitflags, you must create a bitmask and associate a meaning to each bit, e.g:

// ftp constants (bit mask)
FTP_READ = 1<<0; // = 1 (=> bit 1)
FTP_WRITE = 1<<1; // = 2 (=> bit 2)
FTP_EXECUTE = 1<<2; // = 4 (=> bit 3)
FTP_WHATEVER = 1<<3; // = 8 (=> bit 4)

/*
integers are represented as 32 bits in memory (at least on 32 bit machines; I don't know if integers in JavaScript are still 32 bit on 64 bit systems);
thus you can pack at maximum 32 different yes/no (on/off, true/false) informations in one integer variable;
if you try to pack more, no error occurs, but it will not work as expected;
*/

// now we're packing some informaion into an integers (read: we use integers as an array of 32 bits)
userRights = FTP_READ | FTP_WRITE; // user has the right to read and write

userRights = userRights & ~FTP_WRITE; // we withdraw the right to write

userMayWrite = userRights & FTP_WRITE; // see if the user has the permission to write (userMayWrite has either the value 0 or FTP_WRITE)

userRights = userRights ^ FTP_WRITE; // flip the user's permission to write (if it is set, it becomes unset, otherwise it gets set; I don't know where that behavior would be actually useful)

// oh, and for the sake of completeness..
userRights = 0; // user has no rights

userRights = ~0; // user has all rights
dumpfi

subhailc
Apr 12th, 2006, 05:26 PM
thank you.