<no*********@gmail.com> wrote in message

news:11**********************@v46g2000cwv.googlegr oups.com...

I'm learning to program in C and any tutorial or book that I read likes

to briefly touch on birdies operators and then move on without giving

any sort of example application of them. Call me what you will but I

cannot seem to see the purpose for bitwise operators. Especially the

operators bitwise OR ( | ) and bitwise AND ( & ), I'm just not getting

it. I have searched around and really haven't found anything that gave

explanation to why these were necessary to learn or even adequately

describe what they do. Therefor any explanation or recommendation of

the bitwise operators would be greatly appreciated by me. Thanks in

advanced.

The bitwise operators allow you to set, clear, invert, and shift bits in a

value. You may need to do this for many situations: such as programming

hardware registers, graphics, encryption, or extracting an error code.

bitwise or, | , allows you to set bits, any bits in the "oring" value which

are one get set

bitwise and, &, allows you to clear bits, any bits in the "anding" value

which are zero get cleared

bitwise xor, ^, allows you to invert bits, any bits in the "xoring" value

which are set get inverted

bitwise negation,~, allows you to invert all bits, all bits in the "noting"

value are inverted

left bitshift, <<, allows you to shift bits left

right bitshift, >>, allows you to shift bits right

Let's say you want to convert an ASCII unsigned char from lower case to

upper case. The lower case values are +32 above the uppercase values. 32

is nicely expressed as 0x20 hex or 00100000 binary. To convert 'a' to 'A",

we'd use the bitwise and to clear that single bit (bit 5):

val='a';

val&=~0x20; /* 'a' becomes 'A' in ASCII */

/* ~0x20 is 11011111, bit is zero to clear */

/* 'a' is 0x61 hex or 01100001 binary */

/* 'A' is 0x41 hex or 01000001 binary */

To convert 'A' back to 'a', we'd use the bitwise or to set that single bit (

bit 5):

/* val='A'; from above */

val|=0x20; /* 'A' becomes 'a' in ASCII */

/* 0x20 is 00100000, bit is one to set */

/* 'A' is 0x41 hex or 01000001 binary */

/* 'a' is 0x61 hex or 01100001 binary */

HTH,

Rod Pemberton