70 likes | 197 Vues
Bit Manipulation. Binary Numbers. Base 10 numbers are represented by sum of digits times powers of 10. For example: 234 = 2*10 2 +3*10 1 +4*10 0
E N D
Binary Numbers Base 10 numbers are represented by sum of digits times powers of 10. For example: 234 = 2*102+3*101+4*100 Binary numbers are similar, except that the only digits are 1 and 0, and the digits multiply powers of 2. The string "1011" is binary for the decimal number 11. 1011 = 1*23+0*22+1*21+1*20
Bit Operators • The "and" operator: (10 & 3) = 2 • Why? It's clearer expressed in binary numbers: 1010 Apply the rules for and based on each& 0011 row independently. Here 1 = True,------ and 0 = False. Thus, 1 & 1 0010 is True and True = True = 1 • The "or" operator: (10 & 3) = 11 • Why? Again, clearer in binary 1010 = 10| 0011 = 3------ 1011 = 11
Bit Operators • The "xor" or "exclusive or" operator: (10 ^ 3) = 9 • Why? 1010^ 0011------ 1001
Flags • Consider a class Monster that has an integer field named traits. Traits will record capabilities of the Monster in individual bits. Bits can be defined with left shift, e.g. • final static int HAS_FLYING = 1<<0; • final static int HAS_INVISIBILITY = 1<<1; • final static int CAN_SWIM = 1<<2; • final static int FIRE_PROOF = 1<<3;
Flags • To turn a flag on:m.traits |= CAN_SWIM; • To turn a flag off:m.traits &= ~CAN_SWIM; • To toggle a flag:m.traits ^= CAN_SWIM; • The tilde operator "~" inverts the bits on an integer.