с++:具有位位置的快速动作

问题描述 投票:0回答:1

有一个任务:有2个数字:

  • src通过设置相应的位来指定从0到31的数字。
  • dst指定要选择的src中设置的数字的位置

例如:

[src = 0b11010110-数字№1= 1,№2= 2,№3= 4,№4= 6,№5= 7

[mask = 0b00001010-从src提取数字№1,№3

result = 0b01000100

您能告诉我您可以多快完成此操作吗?我写了下面的代码,但是也许您可以做得更好?

int unzip_variant(const int src, const int mask)
{
    int unzipped = 0;

    int pos = 0;

    for (int index = 1; index <= с_size; index ++)
    {
        if (src & (1 << index))
        {
            pos += 1;

            if (mask & (1 << pos))
                unzipped |= (1 << index);
        }
    }

    return unzipped;
}
c++ algorithm c++11 bit-manipulation bit
1个回答
0
投票

我希望,我正确理解了您的问题,并编写了此解决方案:

// x: value, m: mask, for your dataset: unzip(0xd6, 0xa) -> 0x44
unsigned unzip(unsigned x, unsigned m) {
  unsigned bit, mm;
  for(mm = 0, bit = 1; bit <= x; bit <<= 1)
    if(bit & x)
      mm |= bit & m;
    else
      m <<= 1;
  return x & mm;
}
© www.soinside.com 2019 - 2024. All rights reserved.