简体   繁体   中英

How to mask out first 2 MSB bytes of a 64-bit number?

I have a 64-bit unsigned integer . Which contains 0s in the first two MSB bytes. How can I mask out that first two MSB bytes?

uint64 value;
value = 0000 0000 0000 0000 0000 1101 1111 1010 1110 1111 1111 1111 0101 
0101 1101 1101;
uint48 answer;
answer = 0000 1101 1111 1010 1110 1111 1111 1111 0101 
0101 1101 1101;

In the above example, the value is a 64-bit number. I want the answer to contain all the bits other than first 2 bytes. So, that I can pack the answer in a byte array of size 6 . How can I achieve this in C ?

Mask it with 48 1-bits: 0xffffffffffff

uint64_t value = <something>;
uint48_t answer = src & 0xffffffffffff;

But if you know the 2 MSB are zeroes, you don't need to do any masking, just assign the variables:

uint48_t answer = value;

To store them in a byte array, shift by the appropriate number of bytes and mask with 0xff to get a single byte.

uint8_t bytes[6];
for (int i = 0; i < 6; i++) {
    bytes[i] = (value >> (40 - 8 * i)) & 0xff;
}

You can use either the original 64-bit value or the 48-bit value, this works for any size at least 6 bytes.

Make a union with your uint64_t value and an array of Bytes.

typefef union
{
    uint8_t   ByteArray[8];
    uint64_t  Value;
}Array64T;

Array64T   CompleteValue;

CompleteValue.Value = ...
void *copt6lsb(uint64_t val, void *buff)
{
    union{
        uint8_t d8[2];
        uint16_t d16;
    }u16 = {.d8[0] = 0xff};
    char *pos = &val;

    pos = pos + 2 * (u16.d16 == 0xff00);
    memcpy(buff, pos, 6);
    return buff;
}

Good thing is that most compilers then the optimization is on will optimize out the union and will replace the comparison with assignment.

https://godbolt.org/z/JKXDC2

and platforms which allow unaligned access will optimize the memcpy as well

https://godbolt.org/z/c3_ypL

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