符号無し整数の任意のビットを操作するプログラム
#include <stdio.h> /*--- 整数x中のセットされたビット数を返す ---*/ int count_bits(unsigned x) { int count = 0; while (x) { if (x & 1U) count++; x >>= 1; } return (count); } /*--- unsigned型のビット数を返す ---*/ int int_bits(void) { return (count_bits(~0U)); } /*--- unsigned型のビット内容を表示 ---*/ void print_bits(unsigned x) { int i; for (i = int_bits() - 1; i >= 0; i--) putchar(((x >> i) & 1U) ? '1' : '0'); } /*--- xを左にnビットシフトした値を返す ---*/ unsigned lsft(unsigned x, int n) { return ((n >= int_bits()) ? 0 : (x << n)); } /*--- xのposビット目を1にした値を返す ---*/ unsigned set(unsigned x, int pos) { return (x | lsft(1U, pos - 1)); } /*--- xのposビット目を0にした値を返す ---*/ unsigned reset(unsigned x, int pos) { return (x & ~lsft(1U, pos - 1)); } /*--- xのposビット目を反転した値を返す ---*/ unsigned inverse(unsigned x, int pos) { return (x ^ lsft(1U, pos - 1)); } int main(void) { unsigned nx, pos; puts("符号無しの整数xのposビット目を操作します。"); printf("非負の整数xを入力してください:"); scanf("%u", &nx); printf("操作するビット位置posを入力してください:"); scanf("%u", &pos); printf("\nx ="); print_bits(nx); printf("\nset(x, pos) ="); print_bits(set(nx, pos)); printf("\nreset(x, pos) ="); print_bits(reset(nx, pos)); printf("\ninverse(x, pos) ="); print_bits(inverse(nx, pos)); putchar('\n'); return (0); }
実行結果
符号無しの整数xのposビット目を操作します。 非負の整数xを入力してください:12345 操作するビット位置posを入力してください:5 x =00000000000000000011000000111001 set(x, pos) =00000000000000000011000000111001 reset(x, pos) =00000000000000000011000000101001 inverse(x, pos) =00000000000000000011000000101001