将数组缩短为字符的最快方法 [英] Fastest way to downcast an array short to char

查看:51
本文介绍了将数组缩短为字符的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每秒必须处理大约 2000、100 个元素数组.数组以短裤的形式出现在我面前,数据位于高位,需要移位并转换为字符.这是我所能达到的效率,还是有更快的方法来执行此操作?(我必须跳过 2 个值)

I have to process roughly 2000, 100 element arrays every second. The arrays come to me as shorts, w/ the data in the upper bits and need to be shifted and cast to chars. Is this as efficient as I can get, or is there a faster way to perform this operation? (I have to skip 2 of the values)

for(int i = 0; i < 48; i++)
{
    a[i] = (char)(b[i] >> 8);
    a[i+48] = (char)(b[i+50] >> 8);
}

推荐答案

即使移位和按位运算速度很快,您也可以尝试按照注释中的其他建议将短数组作为字符指针进行处理.每个标准都允许这样做,并且对于通用架构而言,它会做预期的事情 - 留下了字节序问题.

Even if shift and bitwise operation are fast, you can try to process the short array as a char pointer as other advised in comments. It is allowed per standard and for common architectures does what is expected - left the endianness problem.

因此您可以尝试首先确定您的字节顺序:

So you could try to first determine your endianness:

bool isBigEndian() {
    short i = 1;   // sets only lowest order bit
    char *ix = reinterpret_cast<char *>(&i);
    return (*ix == 0);   // will be 1 if little endian
}

你的循环现在变成:

int shft = isBigEndian()? 0 : 1;
char * pb = reinterpret_cast<char *>(b);
for(int i = 0; i < 48; i++)
{
    a[i] = pt[2 * i + shft];
    a[i+48] = pt[2 * i + 50 + shft];
}

但对于低级优化,这必须与将在生产代码中使用的编译器和编译器选项进行基准测试.

But as always for low level optimisation, this has to be benchmarked with the compiler and compiler options that will be used in production code.

这篇关于将数组缩短为字符的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆