K& R练习2-7,优化?

时间:2014-12-26 10:43:17

标签: c bit-manipulation kernighan-and-ritchie

我目前正在使用K& R的“C编程语言”学习C.我解决了练习2-7,其中说:

  

写一个函数invert(x,p,n),返回x,其中n位从位置p开始反转(即1变为0,反之亦然),离开其他位没有变化。

这是我的代码(我在这里自愿使用字符):

#include <stdio.h>

#define NUMBER   235
#define POSITION 2
#define AMOUNT   4

unsigned invert(unsigned char x, char p, char n)
{
    unsigned char bitsToInvert = 0, i;

    for (i = 1; i < n; i++) { // Make a number n-bits width, full of 1
        bitsToInvert |= 1;
        bitsToInvert <<= 1;
    }
    bitsToInvert |= 1;

    bitsToInvert <<= p;

    x ^= bitsToInvert;

    return x;
}

int main()
{
    printf("%d\n", invert(NUMBER, POSITION, AMOUNT));
}

我可以为我的代码带来任何优化吗?特别是在for循环上创建了多个n 1位? 谢谢!

2 个答案:

答案 0 :(得分:2)

2^n - 1始终是一个设置了所有n个LSB位的数字。

例如:

2 ^ 3 - 1 = 7  => 111
2 ^ 5 - 1 = 31 => 11111

在你的情况下,你可以通过简单地说:

取消for循环来构造这个数字
bitsToConvert = (1<<n) - 1;

不要忘记处理极端情况。

答案 1 :(得分:0)

替代Thrustmaster所说的,对任何“n”都有效,而不需要指定它,将使用按位而不是空值。

variable = ~(variable ^ variable);
相关问题