演習 2-7
無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。
演習 2-7
x のビット位置 p から n ビットを反転(1 を 0 、 0 を 1 にする)し、他のビットはそのままにした x を返す関数 invert(x, p, n) を書け。
Exercise 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 others unchanged.
演習2-6とほとんど同じ。
#include <stdio.h> /* Answer */ unsigned invert(unsigned x, int p, int n) { n = (n > p + 1) ? p + 1 : n; unsigned mask = ~(~0 << n) << (p - n + 1); return x ^ mask; } void showbits(long num, int size); void _showbits(long num, int remain); int main(void) { unsigned short a = 0x5678; unsigned short b; showbits(a, sizeof(a)); b = invert(a, 11, 12); showbits(b, sizeof(b)); return 0; } void showbits(long num, int size) { _showbits(num, size * 2 - 1); putchar('\n'); } void _showbits(long num, int remain) { static const char bitpattern[16][5] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111", }; if (remain > 0) { _showbits(num >> 4, remain - 1); putchar(','); } printf("%s", bitpattern[ num & 0x0F ]); }