将 MSB 优先转换为 LSB 优先
Convert MSB first to LSB first
我想将无符号短值从 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 分配给最低有效位。基本上,你已经互换了 *(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;
}
我想将无符号短值从 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 分配给最低有效位。基本上,你已经互换了 *(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;
}