Skip to content

Instantly share code, notes, and snippets.

@echiesse
Created December 28, 2019 18:46
Show Gist options
  • Save echiesse/8aca423124d8e05fcf38338007d4c69f to your computer and use it in GitHub Desktop.
Save echiesse/8aca423124d8e05fcf38338007d4c69f to your computer and use it in GitHub Desktop.
Example of struct initialization via memcpy and using a union.
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
class Pair
{
public:
int x;
int y;
void print()
{
cout << "(" << x << ", " << y << ")" << endl;
}
};
union PairBuffer
{
Pair p;
char buffer[8];
int ibuffer[2];
};
void testUnion()
{
cout << endl;
cout << "Testing initializations using a union" << endl;
PairBuffer pb;
pb.p.x = 1;
pb.p.y = 10;
printf("%x%x%x%x.%x%x%x%x\n",
pb.buffer[0], pb.buffer[1], pb.buffer[2], pb.buffer[3],
pb.buffer[4], pb.buffer[5], pb.buffer[6], pb.buffer[7]
);
printf("%x.%x", pb.ibuffer[0], pb.ibuffer[1]);
}
void testMemcpy()
{
cout << endl;
cout << "Testing initialization using memcpy" << endl;
char buffer[8];
int a = 4;
int b = 7;
memcpy(buffer, &a, 4);
memcpy(buffer + 4, &b, 4);
printf("(%i, %i)\n", (int)*buffer, (int)*(buffer+4));
Pair p;
p.x = 1111;
p.y = 2222;
p.print();
memcpy(&p, buffer, 8);
p.print();
}
int main()
{
testMemcpy();
testUnion();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment