Stuart McLachlan
stuart at lexacorp.com.pg
Fri Feb 14 17:12:00 CST 2003
> Hi All, > > I have seen in a couple of programs that use flags to set options > that work by giving a "binary" value, if you will, to each setting. For > example, the first setting has the value 1, the second 2, then 4, > 8,16,32,64,etc. Then it will add up the values of the settings that have > been turned on. So if the 3rd, 5th, and 7th settings were turned on the > value would be 84 (4+16+64). The totaled value generated would be unique, > i.e. no two combinations of settings would produce the same totaled value. > > Here is the part that I get stumped on...how would one program a > function that would take a totaled value and "break it up" into the > individual values that made it up? For example, if given the value 84, it > would "break it up" as 4, 16, and 64. > > Any ideas would be appreciated. > To read and manipulate bits, you normally use the AND, OR and XOR bit functions. AND returns true if both parts are true (ie bits set) So: 84 AND 64 = TRUE because the "64 bit" is set in 84 In general terms: (myNumber AND 2 ^ myBit) returns true if the myBit bit is set For your example: myNumber = 84 (myNumber AND 2 ^ myBit) = false where myBit = 0 (1) = false where myBit = 1 (2) = true where myBit = 2 (4) = true where myBit = 3 (8) = false where myBit = 4 (16) = false where myBit = 5 (32) = true where myBit = 6 (64) = false where myBit = 7 (128) -- Lexacorp Ltd http://www.lexacorp.com.pg Information Technology Consultancy, Software Development,System Support.