Advertisement
rockdrilla

shifty-nifty games with data and endianness

Jan 13th, 2016
416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. // gcc -std=c11 -c -pipe -Wall -Wextra -pedantic -O2 -g0 -fPIC -o test.o test.c
  2. // gcc -Wall -Wextra -pedantic -O2 -g0 -fPIC -o test test.o
  3.  
  4. #include <stdio.h>
  5. #include <stddef.h>
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8.  
  9. typedef union {
  10.         uint32_t h;
  11.         float f;
  12.  
  13.         struct {
  14.                 uint32_t m : 23, e : 8, f : 1;
  15.         } ieee754_le;
  16.  
  17.         struct {
  18.                 uint32_t f : 1, e : 8, m : 23;
  19.         } ieee754_be;
  20.  
  21.         uint8_t c[4];
  22. } test;
  23.  
  24. void dump_bin(size_t val, size_t bits) {
  25.         char * str = NULL;
  26.         char * str_end = NULL;
  27.         size_t temp = val;
  28.         size_t i = 0;
  29.  
  30.         str = malloc(bits + 1);
  31.  
  32.         str_end = str + bits;
  33.         *str_end = 0;
  34.  
  35.         for (i = 0, --str_end; i < bits; ++i, --str_end) {
  36.                 *str_end = '0' + (temp & 1);
  37.                 temp >>= 1;
  38.         }
  39.  
  40.         printf("%s", str);
  41.  
  42.         free(str);
  43. }
  44.  
  45. void dump(const test * val) {
  46.         printf("float:   %f\n", val->f);
  47.         printf("int:     %08x\n", val->h);
  48.  
  49.         printf("bytes:   ");
  50.         for (size_t i = 0; i < sizeof(val->c); ++i) {
  51.                 printf("%02x", val->c[i]);
  52.                 putchar(' ');
  53.         }; putchar('\n');
  54.  
  55.         putchar('\n');
  56.  
  57.         printf("LE-bits: ");
  58.         {
  59.                 dump_bin(val->ieee754_le.f, 1);
  60.                 putchar(' ');
  61.                 dump_bin(val->ieee754_le.e, 8);
  62.                 putchar('\n');
  63.                 dump_bin(val->ieee754_le.m, 23);
  64.                 putchar('\n');
  65.         }; putchar('\n');
  66.  
  67.         printf("BE-bits: ");
  68.         {
  69.                 dump_bin(val->ieee754_be.f, 1);
  70.                 putchar(' ');
  71.                 dump_bin(val->ieee754_be.e, 8);
  72.                 putchar('\n');
  73.                 dump_bin(val->ieee754_be.m, 23);
  74.                 putchar('\n');
  75.         }; putchar('\n');
  76. }
  77.  
  78. int main(void) {
  79.         test z;
  80.  
  81.         printf("// dump float 1234567.0");
  82.         z.f = 1234567.0;
  83.         dump(&z);
  84.  
  85.         printf("// dump int 1234567");
  86.         z.h = 1234567;
  87.         dump(&z);
  88.  
  89.         return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement