简体   繁体   English

编写 C 程序以获取 32 位 integer 并使用联合显示高低字(16 位)

[英]To Write a C Program to take 32 bit integer and display Higher and lower words (16-bits) using union

union breakbit {
    int32_t data;
    int16_t low;
    int16_t high;
} var;

int main() {
    var.data = 0x12345678;
    printf("Initial value:%x\n",var.data);
    printf("Higher bit value:%x\n",var.uplow.high);
    printf("Higher bit value:%x\n",var.uplow.low);

    return 0;
}

The output of the above code is only lower bits and not higher, so anyone can help finding the higher bits value?上面代码的 output 只有低位而不是高位,所以任何人都可以帮助找到高位值吗?

In your example, all three data , low and high overlay one-another.在您的示例中,所有三个datalowhigh都相互叠加。

As per your printf statement, declare the union so:根据您的 printf 语句,声明联合:

union breakbit {
    uint32_t data;
    struct {
        uint16_t low;
        uint16_t high;
    } uplow;
} var;

The meaning of 'low' and 'high` will be different on different machines. “低”和“高”的含义在不同的机器上会有所不同。 (See "Big Endian/Little Endian") (参见“大端/小端”)

EDIT: When dealing with hex values, you probably want to use an unsigned datatype.编辑:在处理十六进制值时,您可能想要使用unsigned数据类型。 I've altered this example to conform.我已更改此示例以符合要求。

To addition to @Fe2O3 good answer and untangle the endian:除了@Fe2O3好的答案并解开字节序:

#include <stdint.h>
#include <stdio.h>

union breakbit {
  uint32_t data32;
  uint16_t data16[2];
};

// Using a C99 compound literal to index the LS half.
#define LS_INDEX ((const union breakbit){ .data32 = 1}.data16[1])

int main(void) {
  union breakbit var = {.data32 = rand() * (RAND_MAX + 1ul) + rand()};
  printf("Initial value:%08lx\n", (unsigned long) var.data32);

  printf("Higher bits value:%04x\n", var.data16[!LS_INDEX]);
  printf(" Lower bits value:%04x\n", var.data16[LS_INDEX]);
}

Output: Output:

Initial value:c0b18ccf
Higher bits value:c0b1
 Lower bits value:8ccf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM