先将MSB转换为LSB

Convert MSB first to LSB first

本文关键字:LSB 转换 MSB 先将      更新时间:2023-10-16

我想先将无符号短值从MSB转换为LSB。执行了以下代码,但不起作用。有人能指出我做的错误吗

#include <iostream>
using namespace std;
int main()
{
  unsigned short value = 0x000A;
  char *m_pCurrent = (char *)&value;
  short temp;
  temp = *(m_pCurrent+1);       
  temp = (temp << 8) | *(unsigned char *)m_pCurrent;
  m_pCurrent += sizeof(short); 
  cout << "temp    " << temp << endl; 
  return 0;
}

这里有一个简单但缓慢的实现:

#include <cstdint>
const size_t USHORT_BIT = CHAR_BIT * sizeof(unsigned short);
unsigned short ConvertMsbFirstToLsbFirst(const unsigned short input) {
  unsigned short output = 0;
  for (size_t offset = 0; offset < USHORT_BIT; ++offset) {
    output |= ((input >> offset) & 1) << (USHORT_BIT - 1 - offset);
  }
  return output;
}

您可以很容易地将其模板化以用于任何数字类型。

错误的是,您首先将value的MSB分配给temp的LSB,然后再次将其移位到MSB,并将value的LSB分配给LSB。基本上,您已经交换了*(m_pCurrent + 1)*m_pCurrent,所以整个事情没有任何影响。

简化代码:

#include <iostream>
using namespace std;
int main()
{
    unsigned short value = 0x00FF;
    short temp = ((char*) &value)[0];           // assign value's LSB
    temp = (temp << 8) | ((char*) &value)[1];   // shift LSB to MSB and add value's MSB
    cout << "temp    " << temp << endl;
    return 0;
}