【问题标题】:Convert MSB first to LSB first将 MSB 先转换为 LSB 先
【发布时间】:2015-06-25 15:29:09
【问题描述】:

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

【问题讨论】:

  • 实际目的是保留在其他功能中,对不起蝙蝠编码风格
  • “它不工作”不是对问题的正确描述。它可以表示从“由于错误 XYZ 无法编译”到“它正在计算 pi 的前 100 位数字,而它应该做其他事情”。
  • 您是指最高有效位还是字节?
  • 你真正想做什么?我的意思是,你想在不同的处理器之间传输二进制数据,还是只是一个练习?
  • B 是指位还是字节?代码看起来像 B 用于字节,但它“不起作用”。请澄清。

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


【解决方案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;
}

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

【讨论】:

  • USHORT_BIT 适用于unsigned short 没有填充位的通常情况。如果unsigned short 有填充,则需要进行不同的USHORT_BIT 计算。
  • 在什么情况下你会说unsigned short被填充了?
  • 规范细节“对于除 unsigned char 以外的无符号整数类型,对象表示的位应分为两组:值位和填充位(后者不需要任何一个)。 "在没有在硬件中实现本机short 类型的系统中,可以使用更广泛类型的填充来实现short。仍然 - 您的位转换代码在正确的轨道上 +1。
  • @chux 那么unsigned short 是否有可能有多个值位除了 16
  • 当然unsigned short 可以> 16位。仍然是 16 是最常见的。它必须至少覆盖 0 到 65535 的范围。如果代码需要精确的 16 位,请使用 uint16_t。顺便说一句:“无符号短整数可能具有除 16 之外的多个值位吗?”是一个很好的可发布问题。
【解决方案2】:

错误是您首先将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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2013-05-17
    • 2011-11-09
    • 2013-12-24
    相关资源
    最近更新 更多