Frage

So while reading the K&R "The C Programming Language" I came across this exercise:

Question: Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

What I don't understand is how to count the bit position, should I start from 1 or 0?

For example with the exercise in mind it would be: With n = 3, p = 4, X= 00100000 //32, Y= 00001011 //11:

             p
             n n n
  X= 0 0 1 0 0 0 0 0 // Number 32
pos: 8 7 6 5 4 3 2 1

  Y= 0 0 0 0 1 0 1 1 // Number 11
               n n n

That will result to:

        p
        n n n
0 0 1 0 0 1 1 0 // Number 38 

Or it could be:

           p
           n n n
  X= 0 0 1 0 0 0 0 0 // Number 32
pos: 7 6 5 4 3 2 1 0

  Y= 0 0 0 0 1 0 1 1 // Number 11
               n n n

That will result to:

      p
      n n n
0 0 1 0 1 1 0 0 // Number 44 

So my question is: What is the most common way of counting the bit position? Should you start from 0 or from 1?

Thank you for your help!

War es hilfreich?

Lösung

What I don't understand is how to count the bit position, should I start from 1 or 0?

The bit count always starts at 0

Example:

unsigned int x = 8;
unsigned int y = x >> 0; // Here you are saying shift x by 0 bit times 

printf("%d: \n", y);
y = x >> 1; // Here you are saying shift x by 1 bit position to left...
printf("%d: \n", y);

and you know shifting left 1 time means divide by 2. If you are shifting left 0 times means divided by 1 (2 power 0) Hope this message was conveyed to you properly.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top