Created
March 3, 2019 23:00
-
-
Save leptos-null/2cbbd0d17a05eb3c10a160ea16b56f7f to your computer and use it in GitHub Desktop.
Visualizing and understanding IEEE 754 floating point values
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
// | |
// floating.c | |
// funbits | |
// | |
// Created by Leptos on 8/18/18. | |
// Copyright © 2018 Leptos. All rights reserved. | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <limits.h> | |
#define printBitRepresentationBuff(a) \ | |
({ \ | |
size_t _i = sizeof(a) * CHAR_BIT; \ | |
char _buff[_i + 1]; \ | |
char *_buff_p = _buff; \ | |
for (; _i; _i--) { \ | |
*(_buff_p++) = (a & (1 << (_i - 1))) ? '1' : '0'; \ | |
} \ | |
*_buff_p = '\0'; \ | |
puts(_buff); \ | |
}) | |
int main() { | |
union { | |
float floating; | |
uint32_t decimal; | |
struct { | |
uint32_t mantissa : 23; | |
uint16_t exponent : 8; | |
uint8_t sign : 1; | |
} ieee; | |
} single_ex; | |
_Static_assert(sizeof(single_ex) == sizeof(float), "Expecting struct size to match main type size"); | |
_Static_assert(sizeof(single_ex.decimal) == sizeof(single_ex.floating), "Expecting main type size to match representing size"); | |
_Static_assert(sizeof(single_ex.decimal) == sizeof(single_ex.ieee), "Expecting main type size to match expanded form size"); | |
puts("Single precision"); | |
single_ex.floating = 0.15625; | |
printBitRepresentationBuff(single_ex.decimal); | |
printf("%+f\n", single_ex.floating); | |
single_ex.ieee.sign = 1; | |
printf("%+f\n", single_ex.floating); | |
union { | |
double floating; | |
uint64_t decimal; | |
struct { | |
uint64_t mantissa : 52; | |
uint16_t exponent : 11; | |
uint8_t sign : 1; | |
} ieee; | |
} double_ex; | |
_Static_assert(sizeof(double_ex) == sizeof(double), "Expecting struct size to match main type size"); | |
_Static_assert(sizeof(double_ex.decimal) == sizeof(double_ex.floating), "Expecting main type size to match representing size"); | |
_Static_assert(sizeof(double_ex.decimal) == sizeof(double_ex.ieee), "Expecting main type size to match expanded form size"); | |
puts("Double precision"); | |
double_ex.floating = 0.15625; | |
printBitRepresentationBuff(double_ex.decimal); | |
printf("%+f\n", double_ex.floating); | |
double_ex.ieee.sign = 1; | |
printf("%+f\n", double_ex.floating); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment