用C++进行整数字节交换

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)

我的代码有两个问题我希望你可以帮我解决.

  1. 出于某种原因,我的两个字节都是01000000
  2. 我真的不确定如何交换字节.我的老师关于位操纵的注意事项非常破碎,难以理解并且对我没有多大意义.

非常感谢你提前.我真的很感谢你帮助我.

nos*_*nos 20

我认为你过于复杂,如果我们假设一个短路包含2个字节(16位),你需要做的就是

  • 提取高字节 hibyte = (x & 0xff00) >> 8;
  • 提取低字节 lobyte = (x & 0xff);
  • 以相反的顺序组合它们 x = lobyte << 8 | hibyte;

  • @Rob S.:`&`:按位和操作.`>>`和`<<`:位移操作.`|`:按位或操作.这足以让google搜索变得非常简单.或者只是阅读http://en.wikipedia.org/wiki/Bitwise_operation (2认同)

Eva*_*ran 8

看起来你正试图一次交换它们.那有点......疯了.你需要做的是隔离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)


The*_*aul 5

你正在努力工作。

您只需要交换字节。因此,研究如何提取两个字节值,然后如何以相反的方式重新组装它们

(作业所以没有给出完整的答案)

编辑:不知道我为什么要烦恼:) 作业问题答案的有用性是通过 OP(可能还有其他读者)学到的东西来衡量的,这并不能通过直接回答作业问题来最大化......