LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bitwise Operators - C Programming (https://www.linuxquestions.org/questions/programming-9/bitwise-operators-c-programming-536860/)

User Name. 03-12-2007 01:51 PM

Bitwise Operators - C Programming
 
I am reading K&R, and I don't exactly under stand the |, ^, &, and ~. Are these entirely necessary to know? How often do I need to know these?

oneandoneis2 03-12-2007 02:21 PM

When I was working through K&R, bitwise operators gave me some trouble too. When I'd sorted it all out, I wrote this article as a summary. You might find it of some use..

taylor_venable 03-12-2007 02:29 PM

You'll need to use these basically anytime you start dealing with raw bits. In C, this can happen a lot, depending on what you're doing. Maybe you want to check some data that's come over the network to find out if it has a flag set -- use bitwise AND. Or you're passing some options to an OpenGL function -- use bitwise OR. It comes up a lot, actually, if you start doing such low-level things. And if you're not doing low-level things... well, what are you using C for?! :)

osor 03-12-2007 02:34 PM

Quote:

Originally Posted by User Name.
I am reading K&R, and I don't exactly under stand the |, ^, &, and ~. Are these entirely necessary to know? How often do I need to know these?

They are not entirely necessary to know, but you will read code using them (many times for flags). What exactly don’t you understand about them?
Code:

unsigned int a = 42;
unsigned int b = 24;
printf("%u\n", a | b);
printf("%u\n", a & b);
printf("%u\n", a ^ b);

Code:

In binary, a = 101010
and        b = 011000

So for |, you OR each bit
i.e., a | b == 111010 == 58

For &, you AND each bit,
i.e., a & b == 001000 == 8

For ^, you XOR each bit
i.e., a ^ b == 110010 == 50


User Name. 03-12-2007 03:04 PM

Quote:

Originally Posted by oneandoneis2
When I was working through K&R, bitwise operators gave me some trouble too. When I'd sorted it all out, I wrote this article as a summary. You might find it of some use..

That article helped alot, thanks.

osor: That was also helpful.

Thanks for the fast and helpful replies.

graemef 03-12-2007 10:41 PM

Just so that you know your efforts to understand bitwise operators are not wasted, they are implemented in most other languages as well :).


All times are GMT -5. The time now is 01:30 PM.