This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//C++ simple serialization demo, converting struct to char (byte) array and back. | |
//Şamil Korkmaz, January 2023 | |
#include <iostream> | |
#include <string.h> //for memcpy | |
typedef struct { | |
int d; | |
int i; | |
} MY_DATA; | |
void f(char* pData) { | |
//print individual bytes (2 ints = 4+4 = 8 bytes): | |
for (int i=0; i < sizeof(MY_DATA); i++) printf("%x ", pData[i]); | |
printf("\n"); | |
//copy bytes to MY_DATA type: | |
MY_DATA data2; | |
memcpy(&data2, pData, sizeof(MY_DATA)); //copying to data2 causes contents of memory pointed to by pData to be interpreted as MY_DATA | |
std::cout <<"data2.d = " << data2.d << std::endl; | |
std::cout <<"data2.i = " << data2.i << std::endl; | |
pData[1] = 1; //changing second byte from 0 to 1 adds 2^8 = 256 to d value | |
} | |
int main() { | |
MY_DATA data; data.d = 5; data.i = 3; | |
f((char*)&data); //interpret contents of memory pointed to by &data as char | |
std::cout <<"data.d = " << data.d << std::endl; | |
return 0; | |
} |
No comments:
Post a Comment