【问题标题】:K&R Exercise 2-7, optimisations?K&R 练习 2-7,优化?
【发布时间】:2014-12-26 10:43:17
【问题描述】:

我目前正在通过 K&R 的“The C Programming Language”学习 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 位? 谢谢!

【问题讨论】:

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


【解决方案1】:

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

例如:

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

在你的情况下,你可以通过简单地说来取消 for 循环来构造这个数字:

bitsToConvert = (1<<n) - 1;

不要忘记处理极端情况。

【讨论】:

  • 谢谢,我想的还不够多。 ^^
【解决方案2】:

Thrustmaster 所说的另一种方法是,它适用于任何“n”而不需要指定它,它是按位而不是空值。

variable = ~(variable ^ variable);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多