Created
March 3, 2020 22:45
-
-
Save Lewiscowles1986/c9eb51ca15429a11fa2abcc959a177c7 to your computer and use it in GitHub Desktop.
Spelunking through math.h to try to find understanding
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<stdio.h> | |
#include<math.h> | |
#include <stdint.h> | |
#include <string.h> | |
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ | |
#define for_endian(size) for (int i = 0; i < size; ++i) | |
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ | |
#define for_endian(size) for (int i = size - 1; i >= 0; --i) | |
#else | |
#error "Endianness not detected" | |
#endif | |
#define printb(value) \ | |
({ \ | |
typeof(value) _v = value; \ | |
__printb((typeof(_v) *) &_v, sizeof(_v)); \ | |
}) | |
void __printb(void *value, size_t size) | |
{ | |
uint8_t byte; | |
size_t blen = sizeof(byte) * 8; | |
uint8_t bits[blen + 1]; | |
bits[blen] = '\0'; | |
for_endian(size) { | |
byte = ((uint8_t *) value)[i]; | |
memset(bits, '0', blen); | |
for (int j = 0; byte && j < blen; ++j) { | |
if (byte & 0x80) | |
bits[j] = '1'; | |
byte <<= 1; | |
} | |
printf("%s ", bits); | |
} | |
printf("\n"); | |
} | |
int main() { | |
printf("Machine info:\n################\n"); | |
printf("Byte order\n"); | |
printf("%i\n", __BYTE_ORDER__); | |
printf("Big Endian\n"); | |
printf("%i\n", __ORDER_BIG_ENDIAN__); | |
printf("Little Endian\n"); | |
printf("%i\n", __ORDER_LITTLE_ENDIAN__); | |
printf("\n"); | |
printf("Math.h info:\n################\n"); | |
printf("M_PI_2\n"); | |
printf("%0.16f\n", M_PI_2); | |
printb(M_PI_2); | |
printf("M_2_PI\n"); | |
printf("%0.16f\n", M_2_PI); | |
printb(M_2_PI); | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested using GCC 9.1.0 jdoodle.com/a/1UbD