簡體   English   中英

uint8 數據到嵌入式 c 中的 uint32 位

[英]uint8 data to uint32 bits in EMBEDDED c

我通過 uint8 數據從我的微控制器獲取輸入數據,這些數據以 0xff、0x2a 的形式傳輸……這兩個位分別是高值和低值。 我需要將其轉換為 uint_32 var,以便我可以使用 memcpy

例子

1C 1D 1E 1F 20 21 22 23      

如果這是傳輸的值,我如何將它們全部放在一個 uint32 變量中,使用下面的方法我只能得到最后兩位,即 23 而不是整個

void Func(const uint8_t * data){
    uint32_t msgh =0;
    uint32_t msgl=0;
    uint32_t datah =0;
    uint32_t datal=0;

    for(int i= 0; i<dlc;i++){
        msgh=*data >> 4;
        msgl=*data & 0x0f;
        // printf("DATA %x%x",msgh,msgl);  
        memcpy(&datah, &msgh, 4);
        memcpy(&datal, &msgl, 4);
        // printf("msgl=%x\n",msgl);           
        data++;
    }
    printf("DATA%x%x",datah,datal);
}

不需要memcpy處理所有這些東西——提取字節的高半字節和低半字節可以按如下方式完成:

uint32_t high = 0;
uint32_t low  = 0;
unsigned int offset = 0;
for(int i = 0; i < 8; ++i)
{
    high |= ((uint32_t)(*data) >> 4)   << offset;
    low  |= ((uint32_t)(*data) & 0x0f) << offset;
    offset += 4;
    ++data;
}

請注意您需要如何移動偏移量,以便半字節在它們各自的 32 位值中到達它們的正確位置。

另請注意,這假定傳輸數據的字節順序為小端字節序(字節順序必須已知並固定為通信協議定義的一部分。)。

大端順序略有不同:

uint32_t high = 0;
uint32_t low  = 0;
unsigned int offset = 32;
for(int i = 0; i < 8; ++i)
{
    offset -= 4;
    high |= (uint32_t)(*data >> 4)   << offset;
    low  |= (uint32_t)(*data & 0x0f) << offset;
    ++data;
}

(好吧,也可以從 28 開始,並在半字節提取后減去 4,類似於 LE 變體——這個變體反映了我個人對 2 的冪常數的偏好——反正運算次數沒有區別……)。

最后請注意,您可能更願意將轉換和輸出分離到單獨的函數中以實現更好的可重用性,例如

void extract(uint8_t const* data, uint32_t* high, uint32_t* low)
{
    // assign to *high and *low analogously to above
}
// assuming C code; if C++, prefer references:
void extract(uint8_t const* data, uint32_t& high, uint32_t& low);


// or alternatively:

typedef struct
{
    uint32_t high;
    uint32-t low;
} NibblesCombined;

NibblesCombined extract(uint8_t const* data)
{
    // assign to the members of the struct analogously to above
}
// again assuming C; C++ could optionally return a std::pair instead!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM