Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active November 12, 2021 17:10
Embed
What would you like to do?
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