gpt4 book ai didi

c++ - 将 MSB 优先转换为 LSB 优先

转载 作者:行者123 更新时间:2023-11-28 06:12:07 27 4
gpt4 key购买 nike

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

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

关于c++ - 将 MSB 优先转换为 LSB 优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com