首先将MSB转换为LSB

时间:2015-06-25 15:29:10

标签: c++ c visual-c++

我想首先将无符号短值从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;
}

2 个答案:

答案 0 :(得分:1)

这是一个简单但很慢的实现:

#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;
}

您可以轻松地将其模板化以使用任何数字类型。

答案 1 :(得分:0)

错误的是您首先将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;
}
相关问题