Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spelunking through math.h to try to find understanding
#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");
}
@Lewiscowles1986

This comment has been minimized.

Copy link
Owner Author

@Lewiscowles1986 Lewiscowles1986 commented Mar 3, 2020

Tested using GCC 9.1.0 jdoodle.com/a/1UbD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment