Jam Jam - 1 year ago 63
C Question

How to use bit field to get whole row bits?

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

struct __attribute__((__packed__)) sf_header
uint64_t lower: 32;
uint64_t higher: 32;
int main()
struct sf_header h;

// part 1;
h.lower = 15;
h.higher = 1;

printf("lower part: %d\n", h.lower);
printf("higher part: %d\n", h.higher);

//part 2: how to printf the whole 64-bits (a row)
unsigned long int lower = h.lower;
unsigned long int higher = h.higher;
higher = higher << 32;

printf("lower: %ld\n", lower);
printf("higher: %ld\n", higher);

unsigned long int final = lower | higher;
printf("Final: %ld\n", final);

return 0;

It runs on 64-bits and the long int is 8 bytes which is a row sized.

First, I assign two values into the lower 32 bits and higher 32 bits.

What if I want to get the 64 bits and use it?

Do I need to do the part 2 or there is a easy way of bit field to do it?

Answer Source

Weather Vane just fractionally ahead of me...!

You use a union. There's one in the Win32 headers (not sure I like it) called ULARGE_INTEGER but here's a quick union example which paraphases that union:

typedef union {
  struct {
    int32_t LowPart;
    int32_t HighPart;
  } u;
  uint64_t QuadPart;

Thus if you had ULARGE_INTEGER a, a.QuadPart would give you the 64 bit part and a.u.LowPart would give you the low 32 bits. Or high 32 bits if your machine was big-endian!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download