Last active
January 8, 2025 09:45
-
-
Save mhcoma/3afe0f4a990e66366a9fa28d73b7e440 to your computer and use it in GitHub Desktop.
Print binary representation of a floating point number in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
typedef union v32_union { | |
float f; | |
uint32_t u; | |
} v32; | |
typedef union v64_union { | |
double f; | |
uint64_t u; | |
} v64; | |
void print_float_bits (float f) { | |
v32 v; v.f = f; | |
uint32_t mask = 1 << 31; | |
do { | |
if (mask == 0x40000000 || mask == 0x400000) putchar(' '); | |
putchar(v.u & mask ? '1' : '0'); | |
} while (mask >>= 1); | |
} | |
void print_double_bits (double d) { | |
v64 v; v.f = d; | |
uint64_t mask = 1ULL << 63; | |
int count = 63; | |
do { | |
if (mask == 0x4000000000000000 || mask == 0x8000000000000) putchar(' '); | |
putchar(v.u & mask ? '1' : '0'); | |
count--; | |
} while (mask >>= 1); | |
} | |
int main(void) { | |
float a = 3.1415926f; | |
double b = 3.141592653589793238; | |
print_float_bits(a); /* 0 10000000 10010010000111111011010 */ | |
putchar('\n'); | |
print_double_bits(b); /* 0 10000000000 1001001000011111101101010100010001000010110100011000 */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
works pretty well it even follows the IEEE754 standard thank you