开发者

Writing an int to a char array

开发者 https://www.devze.com 2023-03-08 15:40 出处:网络
I\'m writing an emulator in C. Its mem开发者_开发百科ory is byte-addressible so I\'m using a char array, but I need to read/write unaligned 32-bit integers.

I'm writing an emulator in C. Its mem开发者_开发百科ory is byte-addressible so I'm using a char array, but I need to read/write unaligned 32-bit integers.

Currently I'm using *((unsigned int*) &memory[address]), but it seems pretty horrible. What's the best way to do it?


You can use memcpy() directly. For example:

unsigned int x = 10;
unsigned char* memory = malloc(sizeof(unsigned char) * 512);
address = sizeof(unsigned char) * 256;

memcpy(memory + address, &x, sizeof(unsigned int)); 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号