簡體   English   中英

將 unsigned char 數組復制到 uint32_t,反之亦然

[英]Copying unsigned char array to uint32_t, and vice versa

我正在嘗試將 unsigned char 數組迭代復制到 uint_32t 變量(在 4 字節塊中),對 uint_32t 變量執行一些操作,然后將其復制回 unsigned char 數組。

這是我的代碼:

unsigned char byteArray[len]
for (int i=0; i<len; i+=4) {
  uint32_t tmpInt = 0;
  memcpy(&tmpInt, byteArray+(i*4), sizeof(uint32_t));
  // do some operation on tmpInt here
  memcpy((void*)(byteArray+(i*4)), &tmpInt, sizeof(uint32_t));
}

雖然它不起作用。 出了什么問題,我怎樣才能實現我想做的事情?

問題是你在每次迭代時將 4 添加到i乘以 4。你應該使用byteArray + i

此外,正如@WeatherVane 在下面指出的那樣,您的循環將與 sizeof() 更加一致:

for (int i = 0; i < len; i += sizeof(uint32_t))

正如其他人指出的那樣,您通過增加i並將其乘以目標大小來做太多事情。

在此之上

  • 顯示的代碼可能會遇到讀取超出源數組的緩沖區溢出問題。
  • sizeof運算符的計算結果為size_t而不是int
  • 代碼重復多次獨立定義目標的大小。

修復所有問題,結果可能如下所示:

  unsigned char byte_array[len];

  typedef uint32_t target_type;
  const size_t s = sizeof (target_type);

  for (size_t i = 0; i < (len/s)*s; i += s) {
    target_type target;
    memcpy(&target, byte_array + i, s);

    // do some operation on target here

    memcpy(byte_array + i, &target, s);
  }

為了避免typedef ,只需在for循環之外定義目標:

  unsigned char byte_array[len];

  {
    uint32_t target;
    const size_t s = sizeof target;

    for (size_t i = 0; i < (len/s)*s; i += s) {
      memcpy(&target, byte_array + i, s);

      // do some operation on target here

      memcpy(byte_array + i, &target, s);
    }
  }

相當於

byte_array + i

將會

&byte_array[i]

這可能更直觀地閱讀。

為了避免“奇怪的” (len/s)*s ,可以完全不使用索引,而是使用指針:

for (unsigned char p = byte_array; p < byte_array + len; p += s) {
      memcpy(&target, p, s);

      // do some operation on target here

      memcpy(p, &target, s);
    }

在我看來,這是一個更優雅的解決方案。

暫無
暫無

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

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