簡體   English   中英

可變字節數到 Uint32_t

[英]Variable number of bytes to Uint32_t

我制作了這個函數,它解壓收到的 I2C 消息並將各個值放入 uint32_t 數組中。 當我使用固定宏函數將固定數量的 2 個字節放入 uint16_t 時,它會起作用,但我嘗試使用 for 循環將任意數量的字節附加到我的值中,因為不同的 i2c 數據包可能具有不同的值類型。 我的問題在於我做位運算的方式,我的位知識似乎太有限了。 這里的選項 2 有什么問題?

#define BytesToU16LE(B) (       \
      (uint16_t)((B)[1]) << 8   \
    | (uint16_t)((B)[0])        \
)

uint8_t ezi2cBuffer[100]; 

void unpack_i2c_packet(uint8_t nb_values_in_packet, uint8_t bytes_per_value, uint32_t * values, uint8_t buffer_head_size)
{
    uint8_t current_value_bytes[bytes_per_value];   
    uint16_t payload_size = bytes_per_value * nb_values_in_packet;
    uint8_t current_value_index = 0;
    
    if(!nb_values_in_packet | !bytes_per_value)
        return;
    
    for(int i = 0; i < payload_size; i++)
    {        
        current_value_bytes[(i % bytes_per_value) + buffer_head_size] = ezi2cBuffer[i + buffer_head_size]; // message head does not contain values, separate from payload
        
        if((i % bytes_per_value) == (bytes_per_value - 1))
        {
            /* OPTION 1 WITH MACRO WORKS */
            values[current_value_index] = BytesToU16LE(current_value_bytes);
            
            /* OPTION 2 FOR LOOP PUTS RANDOM DATA IN MY VAR ARRAY! */
            for(int bi = 0; bi < bytes_per_value; bi ++)
            {
                values[current_value_index] |= ((uint32_t)(current_value_bytes[bi]) << (bi * 8));    
            }
   
            current_value_index++;
        }
    }
}

values[current_value_index]未在選項 2 中初始化。您應該將其初始化為零,否則循環后的值將取決於循環前的值。

            /* OPTION 2 FOR LOOP PUTS RANDOM DATA IN MY VAR ARRAY! */
            values[current_value_index] = 0; /* add this */
            for(int bi = 0; bi < bytes_per_value; bi ++)
            {
                values[current_value_index] |= ((uint32_t)(current_value_bytes[bi]) << (bi * 8));    
            }

暫無
暫無

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

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