将uint64_t转换为unsigned char serialized [8]

时间:2016-03-03 10:49:17

标签: c++

我正在尝试将uint64_t值转换为unsigned char数组。目前我的职能是与uint32_t合作。但是一旦我尝试转换64位值,结果就会不同。

有人看到了错误吗?

#include <iostream>
#include <inttypes.h>

using namespace std;

void serialize_uint64(const uint64_t integer, unsigned char * const serializedInteger);
uint64_t deserialize_uint64(unsigned char * const serializedInteger);

int main (int argc, char *argv[])
{
    uint64_t test64 = 0xFF/*FFFFFFFFFFFFFF;*/;

    unsigned char serialized64[8];
    memset(serialized64, 0x00, sizeof(serialized64));

    serialize_uint64(test64, serialized64);

    printf("%llu = %llu\n", test64, deserialize_uint64(serialized64));

    return 0;
}

void serialize_uint64(const uint64_t integer, unsigned char * const serializedInteger)
{
    serializedInteger[0] = integer >> 56;
    serializedInteger[1] = integer >> 48;
    serializedInteger[2] = integer >> 40;
    serializedInteger[3] = integer >> 32;
    serializedInteger[4] = integer >> 24;
    serializedInteger[5] = integer >> 16;
    serializedInteger[6] = integer >> 8;
    serializedInteger[7] = integer;
}

uint64_t deserialize_uint64(unsigned char * const serializedInteger)
{
    uint64_t converted = 0;

    converted = (converted << 8) | serializedInteger[0];
    converted = (converted << 8) | serializedInteger[1];
    converted = (converted << 8) | serializedInteger[2];
    converted = (converted << 8) | serializedInteger[3];
    converted = (converted << 8) | serializedInteger[4];
    converted = (converted << 8) | serializedInteger[5];
    converted = (converted << 8) | serializedInteger[6];
    converted = (converted << 8) | serializedInteger[7];
    converted = (converted << 8) | serializedInteger[8];

    return converted; // 4294967295
}

1 个答案:

答案 0 :(得分:1)

你有off-by-one error,你解码9个字节。这样:

converted = (converted << 8) | serializedInteger[8];

不应该在那里。注意索引是如何8,即它接受第9个不存在的字节。