将字节数组转换为uint64_t?

问题描述 投票:0回答:2

我有一个称为内存的大字节数组,我正在尝试将其中 8 个字节转换为 uint64_t。我正在尝试以大端打印数字。

到目前为止我有这个:

uint64_t value =  (uint64_t)(memory[256]) | //location contains byte 88
   (uint64_t)(memory[257]) << 8  |          //77
   (uint64_t)(memory[258]) << 16 |          //66
   (uint64_t)(memory[259]) << 24 |          //55
   (uint64_t)(memory[260]) << 32 |          //44
   (uint64_t)(memory[261]) << 40 |          //33
   (uint64_t)(memory[262]) << 48 |          //22
   (uint64_t)(memory[263]) << 56;           //11

我像这样打印:

printf("0x%x", value);

输出是

0x55667788
,但我希望输出是
0x1122334455667788

有关如何修复上述代码以打印的任何建议

0x1122334455667788

解决方案:打印语句需要是:

printf("0x%lx", value);
c arrays bitwise-operators bit-shift endianness
2个回答
0
投票

格式说明符

%lx
可以发挥作用,因为
unsigned long
类型在您的系统上恰好至少有 64 位。 C 标准不保证这一点,事实上它在 64 位 Microsoft Windows 上只有 32 位。
unsigned long long
保证至少有64位,所以你可以使用这个:

printf("0x%llx\n", (unsigned long long)value);

如果您的编译器和C库支持C99或更高版本的标准,您可以使用

<inttypes.h>
中定义的宏:

printf("0x%" PRIx64 "\n", value);

0
投票

下一个代码对我有用:

constexpr
uint64_t pack_bytes_to_u64(
    uint8_t byte_0,
    uint8_t byte_1,
    uint8_t byte_2,
    uint8_t byte_3,
    uint8_t byte_4,
    uint8_t byte_5,
    uint8_t byte_6,
    uint8_t byte_7
)
{
    static_assert(sizeof(uint64_t) == 8, "uint64_t not holds exactly 8 bytes"); // Paranoid check

    return
        (static_cast<uint64_t>(byte_0) << 56) |
        (static_cast<uint64_t>(byte_1) << 48) |
        (static_cast<uint64_t>(byte_2) << 40) |
        (static_cast<uint64_t>(byte_3) << 32) |
        (static_cast<uint64_t>(byte_4) << 24) |
        (static_cast<uint64_t>(byte_5) << 16) |
        (static_cast<uint64_t>(byte_6) <<  8) |
        (static_cast<uint64_t>(byte_7)      );
}

// Compile-time correctness checks:

static_assert( pack_bytes_to_u64(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07) == uint64_t{0x0001020304050607}, "Test failed");
static_assert( pack_bytes_to_u64(0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00) == uint64_t{0x0706050403020100}, "Test failed");

static_assert( pack_bytes_to_u64(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08) == uint64_t{0x0102030405060708}, "Test failed");
static_assert( pack_bytes_to_u64(0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x01, 0x02) == uint64_t{0xAABBCCDDEEFF0102}, "Test failed");
© www.soinside.com 2019 - 2024. All rights reserved.