【发布时间】:2011-12-15 03:22:41
【问题描述】:
我有一个真正用作字节数组而不是用于存储文本的 char 数组。在数组中,有两个特定字节表示我需要存储到无符号 int 值中的数值。下面的代码解释了设置。
char* bytes = bytes[2];
bytes[0] = 0x0C; // For the sake of this example, I'm
bytes[1] = 0x88; // assigning random values to the char array.
unsigned int val = ???; // This needs to be the actual numeric
// value of the two bytes in the char array.
// In other words, the value should equal 0x0C88;
我不知道该怎么做。我认为这将涉及指针的一些转换和重铸,但我无法让它工作。我怎样才能实现我的最终目标?
更新
感谢 Martin B 的快速响应,但这不起作用。具体来说,就我而言,这两个字节是0x00 和0xbc。显然我想要的是0x000000bc。但是我在 unsigned int 中得到的是0xffffffbc。
Martin 发布的代码是我的实际原始代码,只要所有字节都小于 128(即正符号字符值),它就可以正常工作。
【问题讨论】:
-
您不会想要使用指针,因为
unsigned int的大小不太可能与char[2]相同。