简体   繁体   中英

Represent 128 bit integer as two 64 bit integers in C++

I have a situation in my application where the application is using a 128 bit integer (specifically, a __uint128_t ), and at some point the application needs to encode this 128 bit integer as two 64 bit integers ( __uint64_t ).

(Just assume for the sake of this question that it must encode them like that -- this question is not about alternative ways to encode it)

How can I do this? I must be able to encode and decode.

void encode(__uint128_t src, __uint64_t &dest1, __uint64_t &dest2)
{
    // ...
}

void decode(__uint64_t src1, __uint64_t src2, __uint128_t &dest)
{
    // ...
}

Example usage:

__uint128_t bigIntBefore = 999999999999999999;
__uint64_t smallInt1;
__uint64_t smallInt2;
encode(bigIntBefore, smallInt1, smallInt2);

// ... later

__uint128_t bigIntAfter;
decode(smallInt1, smallInt2, bigIntAfter);
// bigIntAfter should have a value of '999999999999999999'

Umm, why not just do:

void encode(__uint128_t src, __uint64_t &dest1, __uint64_t &dest2)
{
    constexpr const __uint128_t bottom_mask = (__uint128_t{1} << 64) - 1;
    constexpr const __uint128_t top_mask = ~bottom_mask;
    dest1 = src & bottom_mask;
    dest2 = (src & top_mask) >> 64;
}

void decode(__uint64_t src1, __uint64_t src2, __uint128_t &dest)
{
    dest = (__uint128_t{src2} << 64) | src1;
}

?

Of course, this might be kind of futile, since __uint128_t may already be just 2 64-bit values. Also, prefer returning a value rather than using lvalue-references:

std::pair<__uint64_t,__uint64_t> encode(__uint128_t src)
{
    constexpr const __uint128_t bottom_mask = (__uint128_t{1} << 64) - 1;
    constexpr const __uint128_t top_mask = ~bottom_mask;
    return { src & bottom_mask, (src & top_mask) >> 64 };
}

__uint128_t decode(__uint64_t src1, __uint64_t src2)
{
    return (__uint128_t{src2} << 64) | src1;
}

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