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