Reading a long from a struct on 32 bit system(C)

限于喜欢 提交于 2019-12-24 09:15:47

问题


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_t is guaranteed to be a 64-bit unsigned, on any system.
  • UINT64_C will append the correct suffix (typically UL or ULL).
  • PRIu64 will 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!