Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Đếm bit 1 trong biểu diễn float trong C

Đếm số bit 1 trong biểu diễn IEEE 754 single-precision của float.

Ví dụ

0.15625 → 6 bit 1

Ý tưởng

  • Ép địa chỉ float sang char*
  • Duyệt 4 byte (sizeof(float))
  • Đếm bit 1 mỗi byte (Brian Kernighan: n &= n-1)

Code

#include <stdio.h>

int count_bits_char(char c) {
    unsigned int cnt = 0;
    unsigned char x = c;
    while (x) { x &= (x-1); cnt++; }
    return cnt;
}

int count_float_bits(float f) {
    unsigned char* p = (unsigned char*)&f;
    int total = 0;
    for (int i = 0; i < sizeof(float); i++)
        total += count_bits_char(p[i]);
    return total;
}

int main() {
    float x = 0.15625f;
    printf("Bit 1 cua %f: %d", x, count_float_bits(x));
    return 0;
}

Kết quả

Bit 1 cua 0.156250: 6