Rob*_* S. 7 c++ byte bit-manipulation
我正在为我的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;
}
Run Code Online (Sandbox Code Playgroud)
和
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;
}
Run Code Online (Sandbox Code Playgroud)
我的代码有两个问题我希望你可以帮我解决.
非常感谢你提前.我真的很感谢你帮助我.
nos*_*nos 20
我认为你过于复杂,如果我们假设一个短路包含2个字节(16位),你需要做的就是
hibyte = (x & 0xff00) >> 8;lobyte = (x & 0xff);x = lobyte << 8 | hibyte;看起来你正试图一次交换它们.那有点......疯了.你需要做的是隔离2个字节,然后做一些移位.让我们分解一下:
uint16_t x = 258;
uint16_t hi = (x & 0xff00); // isolate the upper byte with the AND operator
uint16_t lo = (x & 0xff); // isolate the lower byte with the AND operator
Run Code Online (Sandbox Code Playgroud)
现在你只需要以相反的顺序重新组合它们:
uint16_t y = (lo << 8); // shift the lower byte to the high position and assign it to y
y |= (hi >> 8); // OR in the upper half, into the low position
Run Code Online (Sandbox Code Playgroud)
当然,这可以用更少的步骤完成.例如:
uint16_t y = (lo << 8) | (hi >> 8);
Run Code Online (Sandbox Code Playgroud)
或者不使用任何临时变量进行交换:
uint16_t y = ((x & 0xff) << 8) | ((x & 0xff00) >> 8);
Run Code Online (Sandbox Code Playgroud)
你正在努力工作。
您只需要交换字节。因此,研究如何提取两个字节值,然后如何以相反的方式重新组装它们
(作业所以没有给出完整的答案)
编辑:不知道我为什么要烦恼:) 作业问题答案的有用性是通过 OP(可能还有其他读者)学到的东西来衡量的,这并不能通过直接回答作业问题来最大化......