Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

นับ set bits ใน floating point number ใน C


โจทย์: กำหนดค่า floating point หาจำนวน set bits ใน binary representation

ตัวอย่าง 0.15625 มี 6 set bits คอมไพเลอร์ C ใช้ single precision floating point representation ดูเป็น:

นับ set bits ใน floating point number ใน C

เพื่อแปลงเป็น bit values ใส่ตัวเลขใน pointer แล้ว cast pointer เป็น char* ประมวลผลแต่ละไบต์ นับ set bits ของแต่ละ char

ตัวอย่างโค้ด

#include <stdio.h> int char_set_bit_count(char number) { unsigned int count = 0; while(number != 0) { number &= (number-1); count++; } return count; } int count_float_set_bit(float x) { unsigned int n = sizeof(float)/sizeof(char); int i; char *ptr = (char *)&x; int count = 0; for(i = 0; i < n; i++) { count += char_set_bit_count(*ptr); ptr++; } return count; } main() { float x = 0.15625; printf("Binary representation of %f has %u set bits", x, count_float_set_bit(x)); }

ผลลัพธ์

Binary representation of 0.156250 has 6 set bits