Jump to content

» «

Bitwise operators

1 reply to this topic
  • Swoorup

    Foot Soldier

  • Feroci
  • Joined: 28 Oct 2008
  • Nepal


Posted 07 April 2012 - 03:54 PM

What are bitwise operators exactly used for? What are its applications and in what specific applications is it implemented? I fairly know that they are used for manipulating individual bits. But I want to know how are they implemented mostly and what advantages and disadvantages they provide.

  • K^2

    Vidi Vici Veni

  • Moderator
  • Joined: 14 Apr 2004
  • United-States
  • Best Poster [Programming] 2015
    Most Knowledgeable [Web Development/Programming] 2013
    Most Knowledgeable [GTA Series] 2011
    Best Debater 2010


Posted 10 April 2012 - 02:15 AM

Masking, flags, whatever. There are a bunch of uses. Flags is the most straightforward and common. Say you have a bunch of boolean values to store. Keeping a variable for each is a pain. Instead, you can keep a single integer value, and have it hold 32 boolean values. How do you access individual bits for that? Bitwise operations. Say you declared it as "int flags;". If you want to read the flag 3rd bit, just use (flags & 0x4). Alternatively, if you need to compute the flag position, you can use shifts. (flags & (1<<3)) does the same thing. Setting a flag can be done with OR. flags|=0x04. Or you can specify a bunch of flags at once. flags=0x01|0x04|0x10. Typically, you'd have defines for each of these, so flags are named rather than numbered.

Another common thing is encoding/decoding compressed streams. Data in these usually has variable bit length, so a symbol may start in one byte and end in another. Then you need to pull specific bits to reconstruct the symbol. For specific examples, you can take a look at Deflate algorithm used in Zip, GZip, PNG, etc. Or for something a little more straight forward, GIF image encoding.

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users