_int64 bit field

I need to use a 6-byte (48-bit) bit field in a structure that I can use as an unsigned integer for comparison, etc. Something like the following:

pack (1)
struct my_struct {
  _int64 var1:48;
} s;

if (s.var >= 0xaabbccddee) { // do something }

But for some reason, in 64-bit Windows, sizeofthis structure always returns 8 bytes instead of 6 bytes. Any pointers appreciated?

+1
source share
3 answers

You used _int64and therefore sizeofreturns 8. Its how you decided to use up to 48 bits of the available 64 bits. Even if we declare something like this -

struct my_struct {
  _int64 var1:1;
} s;

sizeof 8. , - . _int64 , , 8 .

+3

, , _int64 8 .

, , , . - 16 32- ( 16- ) .

:

struct my_struct
{
  uint16_t high;
  uint32_t low 
} s;

if (   (s.high > 0xaa)
    || (   (s.high == 0xaa)
        && (s.low >= 0xbbccddee)))
{ ... do something ... }

#pragma pack, .

+1

Google. , __attribute__((packed)).

http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Type-Attributes.html

  24 typedef struct __uint48_t uint48_t;                                             
  25 struct __attribute__((packed)) __uint48_t {                                     
  26     uint64_t _m:48;                                                             
  27 };      

 29 void test()                                                                     
 30 {                                                                               
 31     uint48_t a;                                                                 
 32     a._m = 281474976710655;                                                     
 33     printf("%llu", a._m);                                     
 34     printf("%u", sizeof(a));                                                  
 35                                                                                 
 36     a._m = 281474976710656;                                                     
 37     printf("%llu", a._m);                                                     
 38 }                   

 main1.c: In function ‘test:
 main1.c:36:2: warning: large integer implicitly truncated to unsigned type [-Woverflow]

 $ ./a.out 
 281474976710655
 6
 0

, , Windows, .

, , .

By the way, I still don’t know what is the best way to resolve this issue. Using struct makes things a little awkward (do you need to call a._minstead a, could we handle this?) But at least it seems safer than just using uint64_t.

-1
source

All Articles