简体   繁体   中英

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?

In your example, all three data , low and high overlay one-another.

As per your printf statement, declare the union so:

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. I've altered this example to conform.

To addition to @Fe2O3 good answer and untangle the endian:

#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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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