简体   繁体   English

如何屏蔽64位数字的前2个MSB字节?

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

I have a 64-bit unsigned integer . 我有一个64-bit unsigned integer Which contains 0s in the first two MSB bytes. 在前两个MSB字节中包含0s How can I mask out that first two MSB bytes? 如何屏蔽前两个MSB字节?

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. 在上面的示例中,该值为64位数字。 I want the answer to contain all the bits other than first 2 bytes. 我希望答案包含除前2个字节以外的所有其他位。 So, that I can pack the answer in a byte array of size 6 . 因此,我可以将answer包装在大小为6的字节数组中。 How can I achieve this in C ? 我如何用C实现呢?

Mask it with 48 1-bits: 0xffffffffffff 用48个1位掩码: 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: 但是,如果您知道2个MSB为零,则无需进行任何屏蔽,只需分配变量即可:

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. 要将它们存储在字节数组中,请移动适当数量的字节,并使用0xff进行掩码以获得单个字节。

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. 您可以使用原始的64位值或48位值,这适用于至少6个字节的任何大小。

Make a union with your uint64_t value and an array of Bytes. 与您的uint64_t值和字节数组进行联合。

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 https://godbolt.org/z/JKXDC2

and platforms which allow unaligned access will optimize the memcpy as well 允许不对齐访问的平台也将优化memcpy

https://godbolt.org/z/c3_ypL https://godbolt.org/z/c3_ypL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM