Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdint.h>
- #include <string.h>
- #include <malloc.h>
- typedef unsigned char byte;
- typedef struct {
- uint8_t just_a_byte;
- int16_t int16_with_sign;
- uint8_t text_length;
- char *text;
- } data_t;
- void serialize(const data_t *data, byte *dst) {
- unsigned int p = 0;
- dst[p++] = data->just_a_byte;
- dst[p++] = (int8_t)(data->int16_with_sign >> 8);
- dst[p++] = (uint8_t)(data->int16_with_sign & 0xff);
- dst[p++] = data->text_length;
- strcpy((char *)(dst + p), data->text);
- }
- void deserialize(const byte *array, data_t *data) {
- unsigned int p = 0;
- data->just_a_byte = array[p++];
- data->int16_with_sign = (array[p++] << 8);
- data->int16_with_sign |= array[p++];
- data->text_length = array[p++];
- data->text = (char *)malloc(data->text_length);
- memcpy(data->text, (char *)(array + p), data->text_length);
- }
- int main()
- {
- data_t data = {
- .just_a_byte = 0x12,
- .int16_with_sign = -4567, // = 0xEE29
- .text_length = 6,
- .text = (char *)malloc(6)
- };
- strcpy(data.text, "kissa");
- // Serialize
- byte serialized[16] = { 0 };
- serialize(&data, serialized);
- for (unsigned int i = 0; i < 16; i++)
- printf("%02x ", serialized[i]);
- // Deserialize
- data_t new_data;
- deserialize(serialized, &new_data);
- printf("\njust_a_byte: %x, int16_with_sign: %d, text: %s\n",
- new_data.just_a_byte, new_data.int16_with_sign, new_data.text);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement