Practical Application of Bitwise Operators
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
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. :)
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.
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.
链接地址: http://www.djcxy.com/p/57602.html上一篇: PHP运算符差异&&和“和”
下一篇: 位运算符的实际应用