1 / 6

Bit Manipulation

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

Download Presentation

Bit Manipulation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Bit Manipulation

  2. 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

  3. 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

  4. Bit Operators • The "xor" or "exclusive or" operator: (10 ^ 3) = 9 • Why? 1010^ 0011------ 1001

  5. 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;

  6. 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.

More Related