且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数组的值设置为单个变量

更新时间:2023-01-31 20:29:50

使用并集,但请记住字节序.

Use union but remember about the endianes.

 union 
 {
      uint8_t u8[8];
      uint64_t u64;
  }u64;


typedef联合{uint8_t u8 [8];uint64_t u64;} u64;


typedef union { uint8_t u8[8]; uint64_t u64; }u64;

typedef enum
{
    LITTLE_E,
    BIG_E,
}ENDIANESS;

ENDIANESS checkEndianess(void)
{
    ENDIANESS result = BIG_E;
    u64 d64 = {.u64 = 0xff};
    if(d64.u8[0]) result = LITTLE_E;

    return result;
}

uint64_t arrayToU64(uint8_t *array, ENDIANESS e) // for the array BE
{
    u64 d64;
    if(e == LITTLE_E)
    {
        memmove(&d64, array, sizeof(d64.u64));
    }
    else
    {
        for(int index = sizeof(d64.u64) - 1; index >= 0; index--)
        {
            d64.u8[sizeof(d64.u64) - index - 1] = array[index];
        }
    }
    return d64.u64;
}

int main()
{
    uint8_t BIG_E_Array[] = {0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80};
    ENDIANESS e;

    printf("This system endianess: %s\n", (e = checkEndianess()) == BIG_E ? "BIG":"LITTLE");

    printf("Punned uint64_t for our system 0x%lx\n", arrayToU64(BIG_E_Array, e));
    printf("Punned uint64_t for the opposite endianess system 0x%lx\n", arrayToU64(BIG_E_Array, e == BIG_E ? LITTLE_E : BIG_E));

    return 0;
}