# 《明解C语言入门（第三版）》练习7-4答案

#include<iostream>
using namespace std;

unsigned set(unsigned x, int pos)
{
unsigned y;
if (((x >> (pos - 1)) & 1U) == 0)
{
int v = 1;
for (int i = 2; i <= pos; i++)
v *= 2;
y = x + v;
}
else
y = x;

return y;
}

unsigned reset(unsigned x, int pos)
{
unsigned y;
if (((x >> (pos)) | 0U) == 1)
{
int v = 1;
for (int i = 2; i <= pos; i++)
v *= 2;
y = x - v;
}
else
y = x;

return y;
}

unsigned inverse(unsigned x, int pos)
{
unsigned y;
int v = 1;
if (((x >> (pos)) | 0U) == 1)
{
for (int i = 2; i <= pos; i++)
v *= 2;
y = x - v;
}
else
{
for (int i = 2; i <= pos; i++)
v *= 2;
y = x + v;
}

return y;
}

int count_bits(unsigned x)
{
int bits = 0;
while (x) {
if (x & 1U)
bits++;
x >>= 1;
}
return bits;
}

int int_bits()
{
return count_bits(~0U);
}

void print_bits(unsigned x)
{
int i;
for(i=int_bits()-1;i>=0;i--)
putchar(((x >> i) & 1U) ? '1' : '0');
}

int main()
{
unsigned num,pos;

printf("请输入一个无符号整数：");  scanf_s("%u", &num);
printf("请输入要改变的位：");  scanf_s("%u", &pos);

printf("输入数的二进制形式为：");   print_bits(num);  putchar('\n');

unsigned a, b, c;
a = set(num, pos);
b = reset(num, pos);
c = inverse(num, pos);

printf("第%u位改为1后的值为：%u\n", pos, a);
printf("二进制形式为：");  print_bits(a);  putchar('\n');

printf("第%u位改为0后的值为：%u\n", pos, b);
printf("二进制形式为：");  print_bits(b);  putchar('\n');

printf("第%u位取反后的值为：%u\n", pos, c);
printf("二进制形式为：");  print_bits(c);  putchar('\n');

system("pause");
return 0;
}

03-27
06-11 4362
06-13 1294
06-07 1367
04-04
06-02 2873
06-02 2379
06-10 2516
06-08 2390
06-11 2234
06-10 1942
07-24 239
06-03 7369
12-20 2576
06-07 4632