2

I met this question in an interview. I have no such experience.

So if we have two registers. One with address 0x11111111 and the other 0x22222222. We want to read and write it. The first one is a 32-bit register while the second one is 64-bit. How do we do it in C? Can anyone just give me an example?

Thanks,

10
  • What types do they hold? Commented Jan 24, 2014 at 22:42
  • @self. Not sure. Maybe you can assume as binary?Does it matter? Commented Jan 24, 2014 at 22:42
  • 1
    Registers don't have addresses. C doesn't have registers. Commented Jan 24, 2014 at 22:43
  • @KerrekSB Maybe it's not register. Just assume we want to read and write that piece of memory which can be modified by hardware. We do it in kernel Commented Jan 24, 2014 at 22:45
  • 1
    SOME microcontrollers have registers accessible via addresses. Not all. If you know you're using one of those, it should be obvious how to address it as memory. If you aren't, "C doesn't have registers." Commented Jan 24, 2014 at 22:51

1 Answer 1

1

You can use some kind of pointer or other, for example:

#include <stdint.h>

uint32_t volatile * p = (uint32_t volatile *) 0x11111111;
uint64_t volatile * q = (uint64_t volatile *) 0x22222222;

++*p;  // read-modify-write

(Note that this specific example is almost certainly bogus, since neither address seems to be aligned properly for the respective type.)

As you say, qualifying the pointers as volatile is necessary if the values stored at those addresses can change from outside your program; with volatile you tell the compiler that no assumptions may be made about the value (e.g. constant propagation or common subexpression elimination may not be done for volatile values).

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I noticed that you didn't use the keyword volatile which is mentioned by the interviewer. I think probably we need volatile. And in addition, do you mind telling me why "neither address seems to be aligned properly". I am eager to learn.
@HaoShen: Yeah, volatile makes sense for a memory-mapped access. Alignment is required on many architectures (e.g. a four-byte memory access needs to be at an address divisible by four), but some architectures (like x86) allow byte-aligned access, at some extra cost.
BTW, if I change unit32_t to be int and uint64_t to be long long. Will that work?
@HaoShen: Only if those types have the desired number of bits on your platform.

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.