问题
In C, I have a struct with a member "frequency", which is a long unsigned int. The hardware this code is running on is 32 bits.
The struct has its value set at instantiation.
struct config_list configuration = {
...
.frequency = (long unsigned int)5250000000u,
...
}
In my code, I pass this struct, via pointer, to a subroutine. Inside this subroutine, I don't seem to be able to get the right value, so to check, I put in this:
printf("Config frequency: %lu\n", ptr->frequency);
printf("Derefernced: %lu\n", (*ptr).frequency);
As those are the two ways I believe you would be able to access the struct data from the pointer.
However, in both cases the output I see is 955,032,704. This I recognize as just the first 32 bits of the frequency I set. My question is, why is my long unsigned int being cut to 32 bits? Isn't a "long" supposed to extend the range to 64 bits?
回答1:
5250000000 is 0x1 38EC A480... it just peeks into the 33rd bit.
I would recommend that you use the following:
#include <stdio.h>
#include <stdint.h> /* gives us uint64_t and UINT64_C() */
#include <inttypes.h> /* gives us PRIu64 */
int main(void) {
uint64_t d = UINT64_C(5250000000);
printf("%"PRIu64"\n", d);
return 0;
}
uint64_tis guaranteed to be a 64-bit unsigned, on any system.UINT64_Cwill append the correct suffix (typicallyULorULL).PRIu64will specify the correct format string for a 64-bit unsigned.
On my 64-bit system, it looks like this after the pre-processor (gcc -E):
int main(void) {
uint64_t d = 5250000000UL;
printf("%""l" "u""\n", d);
return 0;
}
And for a 32-bit build, it looks like this (gcc -E -m32):
int main(void) {
uint64_t d = 5250000000ULL;
printf("%""ll" "u""\n", d);
return 0;
}
来源:https://stackoverflow.com/questions/43186729/reading-a-long-from-a-struct-on-32-bit-systemc