gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:50 25 4
gpt4 key购买 nike

我目前正在使用 K&R 的“The C Programming Language”学习 C。我解决了练习 2-7,它说:

Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the other bits unchanged.

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

#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));
}

我可以对我的代码进行任何优化吗?特别是在创建多个 n 1 位的 for 循环中?谢谢!

最佳答案

2^n - 1 始终是所有 n LSB 位都已设置的数字。

例如:

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

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

bitsToConvert = (1<<n) - 1;

不要忘记处理极端情况。

关于c - K&R 练习 2-7,优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27656021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com