dora-sellers
Uploaded by
6 SLIDES
225 VIEWS
70LIKES

Understanding Bit Manipulation and Binary Numbers in Programming

DESCRIPTION

This article explores the concepts of bit manipulation and binary numbers, explaining how decimal and binary systems work with powers of 10 and 2 respectively. It covers essential bit operators such as AND, OR, and XOR, and how to apply these in programming using examples. Additionally, the use of flags in a class structure is illustrated, showcasing how individual bits can represent various traits or capabilities, with techniques for turning flags on, off, and toggling them. This foundation is critical for optimizing code in low-level programming.

1 / 6


Download Presentation

Understanding Bit Manipulation and Binary Numbers in Programming

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
SlideServe
Audio
Live Player
Audio Wave
Play slide audio to activate visualizer