gpt4 book ai didi

c++ - 寻找更高效的位域解码算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:03:46 26 4
gpt4 key购买 nike

我有一个 Visual Studio 2008 C++ 应用程序,我在其中接收到位图(不是图像)。翻转的每个位对应于解码图上的一个位置。

typedef unsigned char BYTE;
const unsigned int COL_COUNT = 8;
const unsigned int ROW_COUNT = 4;

static char g_decode_map[ ROW_COUNT ][ COL_COUNT ] =
{
{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' },
{ 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' },
{ 'q', 'r', 's', 't', 'u', 'v', 'w', 'x' },
{ 'y', 'z', ',', '.', ' ', ':', '-', '+' }
};

// current implementation
void Decode( const BYTE bitmap[ ROW_COUNT ],
const char decode_map[ ROW_COUNT ][ COL_COUNT ],
char decoded[ ROW_COUNT * COL_COUNT ] )
{
int found = 0;
for( int i = 0; i < ROW_COUNT; ++i )
{
for( int j = 0; j < COL_COUNT; ++j )
{
if( std::bitset< COL_COUNT >( bitmap[ i ] ).test( j ) )
{
decoded[ found++ ] = g_decode_map[ i ][ COL_COUNT - j - 1 ];
}
}
}
}

int main( int argc, char* argv[] )
{
BYTE bitmap[ ROW_COUNT ] = { 0x01, 0x80, 0x00, 0x00 };
// expected output { 'h', 'i' } or { 'i', 'h' } order is unimportant

char decoded[ ROW_COUNT * COL_COUNT + 1 ] = { };
Decode( bitmap, g_decode_map, decoded );
printf( "Decoded: %s\r\n", decoded );
return 0;
}

我当前的解码实现工作正常,但让我印象深刻的是可能有更有效的方法来执行此操作。有人可以建议性能更高的算法吗?

最佳答案

与为每个测试的位创建一个位集相比,测试每个位是否使用按位操作设置会更快。尝试这样的事情:

for( int i = 0; i < ROW_COUNT; ++i ) {
for( int j = 0; j < COL_COUNT; ++j ) {
if(bitmap[i] & (1 << j)) {
...

1 << j生成一个只有您想要测试的位的掩码。仅当在 bitmap[i] 中设置该位时,使用位图字节对掩码进行按位与运算才返回 true .这个条件的结果应该等同于你的条件的结果,而且应该快很​​多。

关于c++ - 寻找更高效的位域解码算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com