繁体   English   中英

将uint8_t放在uint64_t内

[英]Put uint8_t inside of a uint64_t

我正在学习C,我想知道是否可以在uint64_t内放置几个uint8_t

例如,假设我要:

1010 1010( uint8_t

并将其放在uint64_t但位于“第7个”位置,例如:

0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

然后我可以添加另一个uint8_t

1111 1111

但在第0位

所以:

0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111

这是我尝试过的方法,但是存在错误,因为它们是不同的类型。

void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    // Somehow put at a location?
    bits = bits << location;
    bits = bits & to_be_added;
}

您有正确的总体思路,但是代码中存在一些错误。 您需要先to_be_added (首先将location值转换为bits ,而不是bytes ),然后再按位或将移位后的值转换为bits

void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    *bits |= ((uint64_t)to_be_added << (location * CHAR_BIT));
}
void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    *bits = *bits | (((uint64_t)to_be_added) << (location*8));
}

为什么不使用工会呢? (当然,如果您不必怀疑耐久度)

typedef union
{
    struct
    {
        uint8_t Byte0;
        uint8_t Byte1;
        uint8_t Byte2;
        uint8_t Byte3;
        uint8_t Byte4;
        uint8_t Byte5;
        uint8_t Byte6;
        uint8_t Byte7;
    };
    uint64_t complete;
}My_uint64T;

My_uint64_t bits;

.....
   //no you could do :



bits.complete = ob0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000;
bits.Byte7 = 0b11111111;

即使比建议的解决方案更冗长,也可以尝试使用并集和数组来使代码保持整洁:

void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added) {
    union {
        uint64_t u64;
        uint8_t u8[8];
    } t;

    t.u64 = *bits;
    t.u8[location] = to_be_added;

    *bits = t.u64;
}
void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    *bits = *bits | (to_be_added << (location*8));
}

暂无
暂无

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

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