在C中复制unsigned int数组

时间:2012-02-24 02:11:18

标签: c arrays int unsigned memcpy

我必须创建一个unsigned int数组来生成IR远程消息。为此,我必须将标头连接到数据位,具体取决于我想要模仿的键。 这就是我所拥有的和问题所在:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const unsigned HEADER[34] = {4608, 4398, 655, 1588, 655, 1588, 655, 1588, 655, 472, 655, 472, 655, 472, 655, 472, 655, 472, 655, 1588, 655, 1588, 655, 1588, 655, 472, 655, 472, 655, 472, 655, 472, 655, 472};

unsigned short BTN_VOL_UP = 0xE01F;

void intToBin(unsigned short a, char* buffer) {
    buffer += 15;
    int i = 15;
    for (i; i >= 0; i--) {
        *buffer-- = (a & 1) + '0';
        a >>= 1;
    }
}

void hexToData(unsigned** data, int code) {
  char* strHex = (char*) malloc(16 * sizeof(char));
  intToBin(code, strHex);
  int i = 0;
  for(i; i < 16; i++) {
    char c = strHex[i];
    *(*data)++ = 655;
    if (c == '1') {
      *(*data)++ = 1588;
    } else {
      *(*data)++ = 472;
    }
  }
  (*data) -= 32;
}

void getCode(unsigned** data, short code) {
  int i = 0;
  for (i; i < 34; i++) {
    *(*data)++ = HEADER[i];
  }
  unsigned* bits = (unsigned*) malloc(32 * sizeof(unsigned));
  hexToData(&bits, code);
  i = 0;
  for (i; i < 32; i++) {
    *(*data)++ = bits[i];
  }
  *(*data)++ = 647;
  *(*data)++ = 0;
  (*data) -= 68;
}

这是代码调用所有这些:

unsigned* data = (unsigned*) calloc(68, sizeof(unsigned));
getCode(&data, BTN_VOL_UP);

之后,我打印HEADER(使用for来打印每个值)和数据变量,但这就是我得到的:

4608 4398 655 1588 655 1588 655 1588 655 472 655 472 655 472 655 472 655 472 655 1588 655 1588 655 1588 655 472 655 472 655 472 655 472 655 472

0 136 1588 655 1588 655 1588 655 472 655 472 655 472 655 472 655 55298 36609 55298 36609 55298 36609 55298 36609 55298 36609 55298 36609 55298 36609 55298 36609 655 655 1588 655 1588 655 1588 655 472 655 472 655 472 655 472 655 472 655 472 655 472 655 472 655 1588 655 1588 655 1588 655 1588 655 1588 647 0 16

HEADER是正确的,但数据全部搞砸了:数据中的标题是完全错误的,实际的数据部分(VOL_UP代码)是正确的,但是在结尾处有一个额外的值,不应该是那里:16。数组应以...... 647,0}结束。

任何想法代码有什么问题?

编辑:我发现了问题,编辑了代码以包含更正。 事实证明我在查找复制值的确切位置时遇到问题,因此我决定手动复制int by int并在末尾减去指针。丑陋,但它确实有效。

1 个答案:

答案 0 :(得分:2)

您的代码会产生以下内容......

4608 4398 655 1588 655 1588 655 1588 655 472 655 472 655 472 655 472 655 472 655 1588 655 1588 655 1588 655 472 655 472 655 472 655 472 655 472 1588 1588 1588 655 655 655 655 655 655 655 655 1588 1588 1588 1588 1588 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 647 0

似乎标题是好的。我不知道密钥生成的算法,所以我不能告诉你值34-49是否正常,但你肯定在50-65范围内有问题。您的代码永远不会将它们设置为任何值。通常malloc不会初始化内存(这取决于标准的库实现),所以你会在50-65内得到垃圾。

相关问题