簡體   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