《c程序设计语言》-2.6~2.8

#include <stdio.h>

unsigned setbits(unsigned x, int p, int n, unsigned y)
{
    return (x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n));
}
int main(void)
{
    unsigned x = 8;
    unsigned y = 4;
    unsigned k;
    int p = 4;
    int n = 3;
    
    k = setbits(x, p, n, y);
    printf("setbits(%u, %d, %d, %u) = %u\n", x, p, n, y, k);

    return 0;
}

以上是2.6.


#include <stdio.h>

unsigned invert(unsigned x,int p,int n)
{
    return x ^ ((~(~0U << n)) << (p+1-n));
}

int main(void)
{
    unsigned x = 8;
    int p = 4, n = 3;

    printf("%u, %d, %d: %u\n", x, n, p, invert(x, p, n));

    return 0;
}

以上是2.7.



#include <stdio.h>

unsigned rightrot(unsigned x, unsigned n)
{
    while (n > 0)
    {
         if ((x & 1) == 1)
             x = (x >> 1) | ~(~0U >> 1);
         else
             x = (x >> 1);
          n--;
    }

    return x;
   }

int main(void)
{
    unsigned x = 8;
    int n = 3;

    printf("%u, %d: %u\n", x, n, rightrot(x,n));

    return 0;
}

以上是2.8.

相关文章
相关标签/搜索