Created
February 22, 2019 00:06
-
-
Save Et7f3/5a5a1e11cf6b5c8c06a58412d3b9f9c4 to your computer and use it in GitHub Desktop.
tool provided to display the binary representation of float and double in C
This file contains hidden or 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 <stdio.h> | |
#include <string.h> | |
void print_float_header() | |
{ | |
printf("%d\n%-10s|%-s|%-8s|%-23s|\n", sizeof(float), "float", "S", "E", "M"); | |
} | |
void print_float(float f) | |
{ | |
char data[sizeof(f)]; | |
int i = sizeof(f) * 8; | |
memcpy(data, &f, sizeof(f)); | |
printf("% lf |", f); | |
while (i--) | |
printf("%c%s", | |
(data[i / 8] & 1 << (i % 8)) ? '1' : '0', (( | |
(i == sizeof(f) * 8 - 1) | |
|| | |
(i == sizeof(f) * 8 - 9) | |
|| | |
(i == 0)) ? "|" | |
: "")); | |
putchar('\n'); | |
} | |
void print_double_header() | |
{ | |
printf("%d\n%-10s|%-s|%-11s|%-52s|\n", sizeof(float), "double", "S", "E", "M"); | |
} | |
void print_double(double f) | |
{ | |
char data[sizeof(f)]; | |
int i = sizeof(f) * 8; | |
memcpy(data, &f, sizeof(f)); | |
printf("% lf |", f); | |
while (i--) | |
printf("%c%s", | |
(data[i / 8] & 1 << (i % 8)) ? '1' : '0', (( | |
(i == sizeof(f) * 8 - 1) | |
|| | |
(i == sizeof(f) * 8 - 12) | |
|| | |
(i == 0)) ? "|" | |
: "")); | |
putchar('\n'); | |
} | |
int main() | |
{ | |
print_float_header(); | |
print_float(0.0f); | |
print_float(-0.0f); | |
print_float(6.f); | |
print_double_header(); | |
print_double(0.0); | |
print_double(-0.0); | |
print_double(5); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment