0

将“无符号字符”数组转换为“无符号短”数组的有效方法是什么?我通常使用以下代码片段来执行此操作。

#define CH_LINE_PIXELS       2291
#define SCANLINE_SIZE        57301
#define CH1_INDEX            2297
#define CH2_INDEX            4592
#define CH3_INDEX            6887
#define CH4_INDEX            9182

unsigned char* pUChar = new unsigned char[SCANLINE_SIZE];

unsigned short *pUS1, *pUS2, *pUS3, *pUS4;
pUS1 = reinterpret_cast<unsigned short *>(&pUChar[CH1_INDEX]);
pUS2 = reinterpret_cast<unsigned short *>(&pUChar[CH2_INDEX]);
pUS3 = reinterpret_cast<unsigned short *>(&pUChar[CH3_INDEX]);
pUS4 = reinterpret_cast<unsigned short *>(&pUChar[CH4_INDEX]);

unsigned short us1, us2;

for (unsigned int i = 0; i < CH_LINE_PIXELS; i++) 
{   
    us1 = pUChar[CH1_INDEX + 2 * i];
    us2 = pUChar[CH1_INDEX + 2 * x + 1];
    pUS1[x] = us1 * 0x100 + us2;

    us1 = pUChar[CH2_INDEX + 2 * i];
    us2 = pUChar[CH2_INDEX + 2 * i + 1];
    pUS2[x] = us1 * 0x100 + us2;

    us1 = pUChar[CH3_INDEX + 2 * i];
    us2 = pUChar[CH3_INDEX + 2 * i + 1];
    pUS3[x] = us1 * 0x100 + us2;

    us1 = pUChar[CH4_INDEX + 2 * i];
    us2 = pUChar[CH4_INDEX + 2 * i + 1];
    pUS4[x] = us1 * 0x100 + us2;
}
4

2 回答 2

0

那么首先你应该做:

us1 << 8 + us2而不是乘以 0x100,因为您想移动高位的前 8 位,并且移位比乘法更快。

例如,您有us1 = aaaaaaaa(8 位)和us2 = bbbbbbbb(另外 8 位)。将这些字符扩展到短裤将只是在左侧用 8 个零填充它们。

那么上面的公式会给你:

00000000aaaaaaaa
<< 8
aaaaaaaa00000000
+ 00000000bbbbbbbb
aaaaaaaabbbbbbbb

另一方面,您应该为您的结果分配一个新的短裤数组。

于 2011-06-13T08:50:15.817 回答
-1

在字节边界上寻址short可能(或可能不会)导致对齐问题,具体取决于平台。

另外,乘法是非常无效的,为什么不使用移位来代替呢?(一些编译器可能会优化 x * 0x100,但如果他们不这样做 - 当你想要的只是x << 8......时,它会对性能造成巨大影响)

此外,如前所述,reinterpret_cast可能无法按预期工作。

我建议,因为无论如何你都会做分配,将值从数组复制char到单独的数组short。它会消耗一些内存,但会为您节省很多意外崩溃和其他问题的麻烦。

于 2011-06-13T08:49:51.997 回答