Home > OS >  To Write a C Program to take 32 bit integer and display Higher and lower words (16-bits) using union
To Write a C Program to take 32 bit integer and display Higher and lower words (16-bits) using union

Time:08-24

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?

CodePudding user response:

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.

CodePudding user response:

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:lx\n", (unsigned long) var.data32);

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

Output:

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