从32位系统上的结构读取较长内容(C) [英] Reading a long from a struct on 32 bit system(C)

查看:88
本文介绍了从32位系统上的结构读取较长内容(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,我有一个成员为"frequency"的结构,它是一个长无符号int.运行此代码的硬件是32位.

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.

但是,在两种情况下,我看到的输出都是955,032,704.我将其识别为我设置的频率的前32位.我的问题是,为什么我的long unsigned int被削减为32位? "long"不是应该将范围扩展到64位吗?

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?

推荐答案

52500000000x1 38EC A480 ...它只是窥视第33位.

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均保证是64位无符号的.
  • UINT64_C将附加正确的后缀(通常为ULULL).
  • PRIu64将为64位无符号指定正确的格式字符串.
    • 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.
    • 在我的64位系统上,在预处理器(gcc -E)之后看起来像这样:

      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;
      }
      

      对于32位版本,它看起来像这样(gcc -E -m32):

      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;
      }
      

      这篇关于从32位系统上的结构读取较长内容(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆