Intercambio de bytes enteros en C ++
Estoy trabajando en una tarea para mi clase de C ++. La pregunta en la que estoy trabajando dice lo siguiente:
Escriba una función que tome un int corto sin signo (2 bytes) y cambie los bytes. Por ejemplo, si x = 258 (00000001 00000010) después del intercambio, x será 513 (00000010 00000001).
Aquí está mi código hasta ahora:
#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;
}
y
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;
}
Mi código tiene dos problemas. Espero que me puedan ayudar a resolver.
Por alguna razón, mis dos bytes son 01000000Realmente no estoy seguro de cómo cambiaría los bytes. Las notas de mis maestros sobre la manipulación de bits están muy rotas y son difíciles de seguir y no tienen mucho sentido para mí.Muchas gracias por adelantado. Realmente aprecio que me hayas ayudado.