【发布时间】: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 位?
谢谢!
【问题讨论】:
-
2^n - 1或(1<<n) -1将为您提供最后 n 位设置。 :) -
你应该至少使用过
unsigned chars。 -
还有一个练习要求你设置一个位范围,这只是一个异或。
标签: c bit-manipulation kernighan-and-ritchie