0

Possible Duplicate:
practical applications of bitwise operations

I have been programming for several years now and I have always wondered about the practical application of bitwise operators.
In my programming experience, I have not had to utilize the bitwise operators. When are they most commonly used? In my programming career, is it necessary for me to learn these? Thank you. Amicably, James

Community
  • 1
  • 1
James Graham
  • 470
  • 2
  • 8
  • 19
  • Do any kind of low-level work where you are manipulating things binary and you'll find they are *real* useful. Depending on the language you use, you can often pack bit fields into integers and get good memory savings. – Jeremy J Starcher Sep 20 '12 at 20:47

3 Answers3

1

Bitwise operations are frequently used close to the hardware - when packing data, doing compression, or packing multiple booleans into a byte. Bitwise operations map directly to processor instructions, and are often extremely fast.

If you're working with I/O or device interfaces, bitwise operations become very necessary - to separate parts of a bitfield into important data.

Or you could just use it as a fast multiply-by-two. :)

Peter Sobot
  • 2,476
  • 21
  • 20
1

Another fun usage for binary and bit twiddling.

Packing Morse code into a single byte. A . is 0 and a - is 1.

A = .- 
A = 00000001xB
// Add a 'start bit'

A = 00000101xB

Shift the bit around 8 times, start playing sounds when you find the start bit.

    +------- Monitor this position
    V
A = 00000101 // Starting off
A = 00001010 // Nothing yet
A = 00010100 // Still nothing
A = 00101000 // WOw, a lot of nothing
A = 01010000 // Our boring life, we do nothing
A = 10100000 // Wow! A start bit! Prep to play sound.
A = 01000000 // Play a short
A = 10000000 // And play a long.
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
1

I have not needed it lately but back when coding pascal I used it to multiply or divide whenever the divisor or multiplication was a power of 2.

Color was stored in a byte with textcolor in the low 4 bits and background color in the high 4 bits.

Using c << 4 instead if c * 16 ,and c >> 4 instead of c / 16 to save or retrieve background was many times faster.

And retrieving textcolor with c <<4 >> 4 was also faster than c & 15 (bitvize and) for some reason. Probably register related ;) but thats way over my head to :D

But unless you are doing checksum calculations, compression or encryption you probably can do without.

Even if you can store bits in an int many times drivers can optimize things for you any way and in c# you can use Flag enums to automatically pack bit flags into byte, word or integer values.

So I would guess that since you have not found a use, you probably are not ding work in the area where they make sense.

David Mårtensson
  • 7,550
  • 4
  • 31
  • 47