If I have 4 bytes of memory and would like to access this memory as both unsigned long L and char c[4]. What would be the most efficient way to do this in C?
For example, if I set the L to 300 then the bytes will be set to 0x0000012c, if I access the c[3] I would expect to see 0x2c
If I increase c[3] by one, it becomes 0x2d and L now has a value of 301
Thanks
You can create a union
of the two types:
union u1 {
unsigned long l;
char c[sizeof(unsigned long)];
};
Then if you create a variable of the union type, you can write to one member and read the other.
Keep in mind however that the result depends on the endianness of your system. Most x86 based systems are little-endian, meaning the least significant byte comes first. If that's the case, the c[0]
member would actually have the value 2c
.
You could investigate the memory using a union
and type punning:
#include <stdint.h>
#include <stdio.h>
typedef union {
uint32_t L;
char c[sizeof(uint32_t)];
} foo;
int main() {
foo x;
x.L = 123;
printf("%X %X %X %X\n", x.c[0], x.c[1], x.c[2], x.c[3]);
}
The output will probably be 7B 0 0 0
or 0 0 0 7B
depending on the endianess of your machine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With