C中的整数字节交换

新手上路,请多包涵

我正在为我的 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;
}

我的代码有两个问题,希望您能帮我解决。

  1. 由于某种原因,我的两个字节都是 01000000
  2. 我真的不确定如何交换字节。我的老师关于位操作的笔记非常破碎,难以理解,对我没有多大意义。

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

原文由 Rob S. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 998
2 个回答

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;

原文由 nos 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用库函数,以下代码可能有用(在非家庭作业环境中):

 unsigned long swap_bytes_with_value_size(unsigned long value, unsigned int value_size) {
    switch (value_size) {
        case sizeof(char):
            return value;

        case sizeof(short):
            return _byteswap_ushort(static_cast<unsigned short>(value));

        case sizeof(int):
            return _byteswap_ulong(value);

        case sizeof(long long):
            return static_cast<unsigned long>(_byteswap_uint64(value));

        default:
            printf("Invalid value size");
            return 0;
    }
}

至少在使用 MinGW 工具链时,字节交换函数在 stdlib.h 中定义。

原文由 BullyWiiPlaza 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题