我正在为我的 C++ 课做家庭作业。我正在研究的问题如下:
编写一个函数,它接受一个无符号的 short int(2 个字节)并交换字节。例如,如果交换后 x = 258 ( 00000001 00000010 ),则 x 将为 513 ( 00000010 00000001 )。
到目前为止,这是我的代码:
#include <iostream>
using namespace std;
unsigned short int ByteSwap(unsigned short int *x);
int main()
{
unsigned short int x = 258;
ByteSwap(&x);
cout << endl << x << endl;
system("pause");
return 0;
}
和
unsigned short int ByteSwap(unsigned short int *x)
{
long s;
long byte1[8], byte2[8];
for (int i = 0; i < 16; i++)
{
s = (*x >> i)%2;
if(i < 8)
{
byte1[i] = s;
cout << byte1[i];
}
if(i == 8)
cout << " ";
if(i >= 8)
{
byte2[i-8] = s;
cout << byte2[i];
}
}
//Here I need to swap the two bytes
return *x;
}
我的代码有两个问题,希望您能帮我解决。
- 由于某种原因,我的两个字节都是 01000000
- 我真的不确定如何交换字节。我的老师关于位操作的笔记非常破碎,难以理解,对我没有多大意义。
非常感谢您提前。我真的很感谢你帮助我。
原文由 Rob S. 发布,翻译遵循 CC BY-SA 4.0 许可协议
C++23 中的新功能:
标准库现在有一个函数正好提供了这个功能:
原答案:
我认为你把它复杂化了,如果我们假设一个短包含 2 个字节(16 位),你需要做的就是
hibyte = (x & 0xff00) >> 8;
lobyte = (x & 0xff);
x = lobyte << 8 | hibyte;