Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // gcc -std=c11 -c -pipe -Wall -Wextra -pedantic -O2 -g0 -fPIC -o test.o test.c
- // gcc -Wall -Wextra -pedantic -O2 -g0 -fPIC -o test test.o
- #include <stdio.h>
- #include <stddef.h>
- #include <stdlib.h>
- #include <stdint.h>
- typedef union {
- uint32_t h;
- float f;
- struct {
- uint32_t m : 23, e : 8, f : 1;
- } ieee754_le;
- struct {
- uint32_t f : 1, e : 8, m : 23;
- } ieee754_be;
- uint8_t c[4];
- } test;
- void dump_bin(size_t val, size_t bits) {
- char * str = NULL;
- char * str_end = NULL;
- size_t temp = val;
- size_t i = 0;
- str = malloc(bits + 1);
- str_end = str + bits;
- *str_end = 0;
- for (i = 0, --str_end; i < bits; ++i, --str_end) {
- *str_end = '0' + (temp & 1);
- temp >>= 1;
- }
- printf("%s", str);
- free(str);
- }
- void dump(const test * val) {
- printf("float: %f\n", val->f);
- printf("int: %08x\n", val->h);
- printf("bytes: ");
- for (size_t i = 0; i < sizeof(val->c); ++i) {
- printf("%02x", val->c[i]);
- putchar(' ');
- }; putchar('\n');
- putchar('\n');
- printf("LE-bits: ");
- {
- dump_bin(val->ieee754_le.f, 1);
- putchar(' ');
- dump_bin(val->ieee754_le.e, 8);
- putchar('\n');
- dump_bin(val->ieee754_le.m, 23);
- putchar('\n');
- }; putchar('\n');
- printf("BE-bits: ");
- {
- dump_bin(val->ieee754_be.f, 1);
- putchar(' ');
- dump_bin(val->ieee754_be.e, 8);
- putchar('\n');
- dump_bin(val->ieee754_be.m, 23);
- putchar('\n');
- }; putchar('\n');
- }
- int main(void) {
- test z;
- printf("// dump float 1234567.0");
- z.f = 1234567.0;
- dump(&z);
- printf("// dump int 1234567");
- z.h = 1234567;
- dump(&z);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement