

I cannot wrap my head around bit-ops in C, anyone want to give me a guide? - t3rr0r1z3r

I have a problem understanding Binary bitwise operations in C, I tried to do the k&#38;r exercises with no help, and got no where, after trying for days.<p>Can anyone out there recommend a tutorial/guide or give some assistance please, I really would like to understand how this works.<p>Is it me, or is it ordinary to be confused about this?<p>Thanks
======
RiderOfGiraffes
What is your confusion? Do you understand binary representation of numbers?
Can you given us the binary representation of 11? 12? 25? -9?

Do you know what the logical operations are? AND? OR? XOR? NOT? What are the
answers to these:

    
    
      1 AND 1
      1 AND 0
      1 OR x (where x is 0 or 1)
    
    

Without that knowledge you have a problem. With that knowledge the problem
lies elsewhere and we can explore that. If you can work on this is slow time
then I'd be happy to get an email asking questions.

ADDED IN EDIT: Can you give an example of a case or calculation you don't
understand?

~~~
t3rr0r1z3r
Well, the problem is: Write a program setbits(x, p, n, y); which returns x
with the n bits that begin at position p set to the rightmost n bits in y,
leaving the other bits unchanged.

I've tried to solve it.

To answer your questions; Yes, I understand binary representation, 11 is 1011
12 is 1100 25 is 11001 -9 is 1001010 (where the leftmost bit is set to 1)

~~~
RiderOfGiraffes
Well, -9 isn't 1001010, but we can explore that another time.

The real help would be if you showed what you've tried. However:

How can you extract the rightmost (least significant) 3 bits of a number _x_?

How can you move the bits in a number to the left (make them more
significant)?

How can you turn off some bits in a number?

Can you puzzle out how these questions/answers can be glued together to do
what you want?

Have you tried doing it by hand on paper?

Here:

    
    
       x = 1010101010101
       p = 4
       n = 5
       y = 11111111
    

Show us what you actually need to do, step by step.

PS: This probably isn't the forum to have a tutorial on such questions, and
I'm going off line in a few minutes. If no one else answers your questions,
email me.

PPS: Where does this question come from? What resources do you have?

