Serialization Helper

March 23, 2017 ยท View on GitHub

/*

  • serial.h - Serialization helper
  •         DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
    
  •                Version 2, December 2004
    
  • Copyright (C) 2004 Sam Hocevar sam@hocevar.net
  • Everyone is permitted to copy and distribute verbatim or modified
  • copies of this license document, and changing it is allowed as long
  • as the name is changed.
  •        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
    
  • TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    1. You just DO WHAT THE FUCK YOU WANT TO.
  • Why memcpy ? http://stackoverflow.com/a/32095106 */

#ifdef __cplusplus extern "C" { #endif

#include <stdint.h> #include <string.h>

uint16_t inline BsWord(uint16_t x){ return ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8); }

uint32_t inline BsDword(uint32_t x){ return ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24); }

#define BsData(i) ({
_Generic((i),
uint16_t: BsWord(i),
uint32_t: BsDword(i),
default: (i));
})

#define ToData(o, i) ({
memcpy(&o, i, sizeof(i));
})

#define FrData(o, i) ({
memcpy(o, &i, sizeof(i));
})

#define RdData(o, i) ({
ToData(o, i);
i += sizeof(o);
})

#define WrData(o, i) ({
FrData(o, i);
o += sizeof(i);
})

#define RsData(o, i) ({
RdData(o, i);
o = BsData(o);
})

#define WsData(o, i) ({
i = BsData(i);
WrData(o, i);
})

#ifdef __cplusplus } #endif