Skip to content

Instantly share code, notes, and snippets.

@TheServer201
Last active September 7, 2018 04:52
Show Gist options
  • Save TheServer201/9ae5322cd52f76c7d36af15d3b366762 to your computer and use it in GitHub Desktop.
Save TheServer201/9ae5322cd52f76c7d36af15d3b366762 to your computer and use it in GitHub Desktop.
Serialization Helper
/*
* 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
*
* 0. 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
@TheServer201
Copy link
Author

TheServer201 commented Apr 14, 2017

TODO.

  • Force gcc to push large input (>5 bytes) with 4, 2 and 1 bytes primitives.
  • Use internal temporary variable to allow non pointers input or output.
  • Add documentation (doxygen).

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