简体   繁体   中英

Combine two 32bit efficiently? - C

I have a function which expects a 8 bytes long unsigned char.

void f1(unsigned char *octets)
{
  unsigned char i;
  for (i=0;i<8;i++)
    printf("(%d)",octets[i]);
}

This is how I use it while I have one 64bit integer:

  unsigned long long ull = 1;
  f1((unsigned char *) &ull);

(it uses the machine's native endianness.)

My question is, if instead of having 1x64bit integer, I have 2x32bit integers - is there a way to combine them efficiently as an input for this specific function?

  unsigned long int low = 1;
  unsigned long int high = 0;

You could just put them in an array:

unsigned long int lohi[2] = {1, 0};
f1((unsigned char *) lohi);

edit : Using existing variables:

unsigned long int lohi[2] = {lo, hi};

Does a union work portably? If so, it's a good approach...

union {
    struct {
        unsigned char CharArray[8];
    } ub;
    struct {
        unsigned long int IntArray[2];
    } ul;
    unsigned long long ull;
} Foo;

Typecast, bitshift and do bitwise or.

unsigned long int low = 1;
unsigned long int high = 0;
unsigned long long ull = (unsigned long long) high << 32 | low;

You can use a combination of union and struct to keep your namings and not using arrays.

union {
    struct {
        unsigned long int   low  = 0;
        unsigned long int   high = 1;
    };
    unsigned long long int  ull;
};

Use low and high as you would do, and use ull when calling f1 . But notice that writing it this way, you assume a little endian ordering.

Also note that on Linux anh other UNIXes, in 64 bits mode, both long int and long long int are 64 bits (only int is 32 bits). Of what I know, only Windows has long int as 32 bits in 64 bits mode.

Different way of looking at it:

void f1( unsigned char* octet )
{
    f2( octet, octet + 4 );
}

void f2( unsigned char* quad1, unsigned char *quad2 )
{
    unsigned char i;
    for (i=0;i<4;i++)
        printf("(%d)",quad1[i]);
    for (i=0;i<4;i++)
        printf("(%d)",quad2[i]);
}

Works better in C++ when both functions can have the same name.

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