#35880: 在 C語言中 對於數值系統的認知 與 bitwise 操作


900131shawn@gmail.com (nocmos_0623)

學校 : 不指定學校
編號 : 124194
來源 : [140.112.230.169]
最後登入時間 :
2024-06-22 21:19:17
a034. 二進位制轉換 | From: [115.165.216.180] | 發表日期 : 2023-06-21 16:17

#include <stdio.h>

static inline void print_binary(int n)
{
        if (n == 0) {
                putchar('0');
                putchar('\n');
                return;
        }

        // use gcc __builtin_clz 'count leading zeros(clz)'
        int shift = __builtin_clz(n);

        // mask = 0b1000 0000 0000 0000 0000 0000 0000 0000 = 2147483648 = 2^31
        // use variable shift I can know where the first bit start
        unsigned int mask = 0x80000000 >> shift;

        // I used n_shift to shift the bit of value "(n & mask)" to the lowerest bit ,
        // so I can no use branch condition statement (like if else or ?) in while loop.
        // (sizeof(int) << 3) calculate the size of int that is 32 bit
        // and "<< 3" (shift right 3 bit) is faster then "* 8" (multiply by 8).
        size_t n_shift = (sizeof(int) << 3) - shift - 1;

        // if mask = 0x00000000 = 0 then stop
        while (mask) {
                // the result of "(n & mask) >> n_shift)" is either 0 or 1
                // '0' + 0 will not change, and '0' + 1 is '1'
                putchar('0' + ((n & mask) >> n_shift--));
                mask >>= 1;
        }
        putchar('\n');
}

int main(int argc, char const *argv[])
{
        int n = 0;
        while (fscanf(stdin, "%d", &n) != EOF) {
        print_binary(n);
        }
        return 0;
}
 
ZeroJudge Forum