K&Rを読もう(30) 2.9 2進数のダンプをマクロで

2.9はビット演算子の解説です。

ビット演算といえば2進数のダンプが欲しくなる。

型ごとに関数を作るのが面倒なので、マクロを活用してみた。

#include <stdio.h>
#include <stdlib.h>

#define dump(type, bin)                               \
    do {                                              \
        int i;                                        \
        for (i = sizeof (type) * 8 - 1; i >= 0; i--)  \
            putchar('0' + ((bin) >> i & 0x01));       \
        puts("");                                     \
    } while (0)

int main(void)
{
    short mode = 0644;
    short mode_x = mode | 0111;

    dump(short, mode);
    dump(short, mode_x);
    dump(short, mode_x & ~0111);

    printf("%#o\n", mode);
    printf("%#o\n", mode_x);
    printf("%#o\n", mode_x & ~0111);

    return EXIT_SUCCESS;
}
  • do 〜 while(0)はセミコロン対策用ダミー。
  • 0と1しか出ないので、putchar('0' + 〜);で文字列演算してます。
  • GCC専用になるけど、typeの代わりに、typeofを使う手もアリ。
  • メモ:ビット演算子の優先順位はかなり低い。

実行結果。

0000000110100100
0000000111101101
0000000110100100
0644
0755
0644

0644 | 0111で実行属性が付きました。

0755 & ~0111で実行属性が外れます(笑