我正在为我的 C++ 课程做家庭作业。我正在研究的问题如下:
编写一个函数,它接受一个无符号短整型(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;
}
and
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
- 我真的不知道如何交换字节。我的老师关于位操作的笔记非常破碎且难以理解,而且对我来说没有多大意义。
预先非常感谢您。我真的很感谢你对我的帮助。
C++23 中的新功能:
标准库现在有一个函数可以提供这种功能:
#include <iostream>
#include <bit>
int main() {
unsigned short x = 258;
x = std::byteswap(x);
std::cout << x << endl;
}
原答案:
我认为你把它复杂化了,如果我们假设一个短由 2 个字节(16 位)组成,那么你所需要的一切
要做的是
- 提取高字节
hibyte = (x & 0xff00) >> 8;
- 提取低字节
lobyte = (x & 0xff);
- 以相反的顺序组合它们
x = lobyte << 8 | hibyte;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)