用C整数字节交换++ [英] Integer Byte Swapping in C++

查看:177
本文介绍了用C整数字节交换++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的C ++类家庭作业。我的工作的问题如下:

I'm working on a homework assignment for my C++ class. The question I am working on reads as follows:

编写一个函数,接受一个无符号的短整型(2字节)和交换字节。例如,如果在x = 258(00000001 00000010)的交换之后,x是513(00000010 00000001)。

Write a function that takes an unsigned short int (2 bytes) and swaps the bytes. For example, if the x = 258 ( 00000001 00000010 ) after the swap, x will be 513 ( 00000010 00000001 ).

下面是我的code迄今:

Here is my code so far:

#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;
}   

我的code有两个问题,我希望你可以帮我解决。

My code has two problems I am hoping you can help me solve.


  1. 出于某种原因,我的两个字节是01000000

  2. 我真的不知道我怎么会交换字节。我的老师对位操作的注意事项很破,难以遵循,并没有太大的意义了我。

非常感谢你提前。我真的AP preciate你帮我。

Thank you very much in advance. I truly appreciate you helping me.

推荐答案

我觉得你是过于复杂,如果我们假设一个简短由2个字节(16位),所有你需要的
要做的就是

I think you're overcomplicating it, if we assume a short consists of 2 bytes (16 bits), all you need to do is


  • 提取高字节 HIBYTE =(X安培;为0xFF00)GT;&GT; 8;

  • 提取低字节 lobyte =(X安培; 0xFF的);

  • 在相反的顺序将它们结合起来 X = lobyte&LT;&LT; 8 | HIBYTE;

  • extract the high byte hibyte = (x & 0xff00) >> 8;
  • extract the low byte lobyte = (x & 0xff);
  • combine them in the reverse order x = lobyte << 8 | hibyte;

这篇关于用C整数字节交换++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆