I've found a need to reverse the endianness of integer data read from some files I'm working with. So I wrote the following:
Code:
typedef unsigned int uint;
typedef unsigned char byte;
uint reversendian(uint i)
{
union { uint i; byte b[4]; } in, out;
int j;
in.i=i;
for (j=0; j<4; j++)
{
out.b[3-j]=in.b[j];
}
return out.i;
}
I say "uint" and "byte" because I get tired of typing "unsigned int" and "unsigned char" all the time. These typedefs are actually in the header file for the functions in my own library.
This function works for my purposes. But the problem, of course, is that it is not portable, because it assumes a 4-byte size for int or unsigned int. What can I use for the type of data of the parameter, returned value, and innards such that it will serve for either signed or unsigned four-byte integers, but a compiler will reject attempts to use it for other sizes?