Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer indirection when pointer and data widths differ

I want to access a 32-bit data pointed to by an address in a hardware register (which is 64 bits, with only 40 LSb's set). So I do:

paddr_t address = read_hw(); // paddr_t is unsigned long long
unsigned int value  = *(unsigned int*) address; // error: cast to pointer from integer of different size
unsigned int value2 = (unsigned int) *((paddr_t*) address); // error: cast to pointer from integer of different size

What would be the right way to do this without compiler error (I use -Werror)?

like image 993
Jeenu Avatar asked Sep 01 '26 20:09

Jeenu


1 Answers

Nominally with C99 the first option is closest to correct,

uint32_t value = *(uint32_t*)address;

However you may also choose to use the other pointer/integer helpers,

uintptr_t address = read_hw();
uint32_t value = *(uint32_t*)address;
like image 109
Steve-o Avatar answered Sep 04 '26 11:09

Steve-o



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!