【发布时间】:2014-08-22 01:17:46
【问题描述】:
我想将字节数组bytes1 (little endian) 2 x 2 转换为短整数数组,反之亦然。我希望得到最终数组bytes2,等于初始数组bytes1。我有这样的代码:
int i = 0;
int j = 0;
char *bytes1;
char *bytes2;
short *short_ints;
bytes1 = (char *) malloc( 2048 );
bytes2 = (char *) malloc( 2048 );
short_ints = (short *) malloc( 2048 );
for ( i=0; i<2048; i+=2)
{
short_ints[j] = bytes1[i+1] << 8 | bytes1[i] ;
j++;
}
j = 0;
for ( i=0; i<2048; i+=2)
{
bytes2[i+1] = (short_ints[j] >> 8) & 0xff;
bytes2[i] = (short_ints[j]) ;
j++;
}
j = 0;
现在,谁能告诉我为什么我没有bytes2 数组,和bytes1 完全一样?以及如何正确地做到这一点?
【问题讨论】:
-
它们有何不同以及在哪里不同?对于较小的输入,预期和实际输出是多少?
-
输入不小;它是 2048 字节。许多元素不同,它们的索引都在 1000 以上。在索引 1000 以下,所有元素都是相等的。
-
您似乎左移到符号位并将其移回。这是实现定义的,并且可能符号位也被移位。根据经验,按位运算始终使用无符号类型。
-
因为你在使用之前没有初始化
bytes1数组,所以你不知道你会得到什么。 -
不,你不想用有符号字节来做;你会在某个时候投射到
unsigned。
标签: c type-conversion