1

I'm writing an emulator in C. Its memory 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?

4
  • 5
    Note that on some machine architectures, an unaligned 32-bit write like that won't work at all--rather than poor performance, you'll get a crash. So depending on what your target platforms are, you may need to do the writes a byte at a time. Commented May 25, 2011 at 22:46
  • 2
    Also note that for some compilers, an int is not exactly 32 bits, so if you really mean "four bytes" rather than "sizeof(int)", and you care about portability and maintainability, you need to do something different. Commented May 25, 2011 at 22:53
  • 1
    To add one more thing to Kristopher's points. If you want your emulator to be portable to both little and big endian platforms, the correct answer might be a little more complex still than just a memcpy() or other byte-wise copy that can deal with unaligned addresses. I don't know if this is important to you, but if it is it's something you need to think about. Commented May 25, 2011 at 23:03
  • I know about endianness but I don't think it matters much in this case. The emulator will only run in a specific environment. Commented May 25, 2011 at 23:05

1 Answer 1

4

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)); 
Sign up to request clarification or add additional context in comments.

1 Comment

memcpy() is probably the safest way to go, portabilitywise, but if your compiler actually makes a function call every time, you may not be happy with the performance. (But note that many compilers will inline memcpy or replace it with a machine instruction.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.