Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <string.h>
  3. #include <malloc.h>
  4.  
  5. typedef unsigned char byte;
  6.  
  7. typedef struct {
  8. uint8_t just_a_byte;
  9. int16_t int16_with_sign;
  10. uint8_t text_length;
  11. char *text;
  12. } data_t;
  13.  
  14. void serialize(const data_t *data, byte *dst) {
  15. unsigned int p = 0;
  16. dst[p++] = data->just_a_byte;
  17. dst[p++] = (int8_t)(data->int16_with_sign >> 8);
  18. dst[p++] = (uint8_t)(data->int16_with_sign & 0xff);
  19. dst[p++] = data->text_length;
  20. strcpy((char *)(dst + p), data->text);
  21. }
  22.  
  23. void deserialize(const byte *array, data_t *data) {
  24. unsigned int p = 0;
  25. data->just_a_byte = array[p++];
  26. data->int16_with_sign = (array[p++] << 8);
  27. data->int16_with_sign |= array[p++];
  28. data->text_length = array[p++];
  29. data->text = (char *)malloc(data->text_length);
  30. memcpy(data->text, (char *)(array + p), data->text_length);
  31. }
  32.  
  33. int main()
  34. {
  35. data_t data = {
  36. .just_a_byte = 0x12,
  37. .int16_with_sign = -4567, // = 0xEE29
  38. .text_length = 6,
  39. .text = (char *)malloc(6)
  40. };
  41. strcpy(data.text, "kissa");
  42.  
  43. // Serialize
  44. byte serialized[16] = { 0 };
  45. serialize(&data, serialized);
  46. for (unsigned int i = 0; i < 16; i++)
  47. printf("%02x ", serialized[i]);
  48.  
  49. // Deserialize
  50. data_t new_data;
  51. deserialize(serialized, &new_data);
  52. printf("\njust_a_byte: %x, int16_with_sign: %d, text: %s\n",
  53. new_data.just_a_byte, new_data.int16_with_sign, new_data.text);
  54.  
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement