Last active
November 12, 2021 17:10
-
-
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
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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ g++ int_as_array.cpp && ./a.out a: 0xaabbccdd a[0]: 0xdd a[1]: 0xcc a[2]: 0xbb a[3]: 0xaa a: 0xaabbccff