Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active November 12, 2021 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gubatron/51909d0741b8901a8e59d704104c2ef7 to your computer and use it in GitHub Desktop.
Save gubatron/51909d0741b8901a8e59d704104c2ef7 to your computer and use it in GitHub Desktop.
Access and manipulate an int via char array using an union. C Plus plus
#include <iostream>
int main() {
union {
unsigned int a; // 32 bit number, 4 bytes
unsigned char aa[4]; // access a's bytes as an array
};
a = 0xaabbccdd;
printf("a: 0x%x\n", a); // a: 0xaabbccdd
// where: aa[3]=0xaa, a[2]=0xbb, a[1]=0xcc, a[0]=0xdd
for (unsigned int i=0; i < 4; i++) {
printf("a[%d]: 0x%x\n", i, (unsigned int) aa[i]);
}
aa[0]=0xff;
printf("a: 0x%x\n", a);
return 0;
}
@gubatron
Copy link
Author

gubatron commented Nov 12, 2021

$ g++ int_as_array.cpp && ./a.out
a: 0xaabbccdd
a[0]: 0xdd
a[1]: 0xcc
a[2]: 0xbb
a[3]: 0xaa
a: 0xaabbccff

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