try 一 try template <typename T> T transformBigToLittleEndian(const T &BiValue) { unsigned short sizeCount = sizeof(T); T liValue; if (sizeCount == 2) { liValue = ((BiValue & 0xFF00) >> 8) |((BiValue & 0x00FF) << 8); } else if (sizeCount == 4) { liValue = ((BiValue & 0xFF000000) >> 24) | ((BiValue & 0x00FF0000) >> 8) | ((BiValue & 0x0000FF00) << 8) | ((BiValue & 0x000000FF) << 24); } else if (sizeCount == 8) { liValue = ((BiValue & 0xFF00000000000000) >> 56) | ((BiValue & 0x00FF000000000000) >> 40) | ((BiValue & 0x0000FF0000000000) >> 24) | ((BiValue & 0x000000FF00000000) >> 8) | ((BiValue & 0x00000000FF000000) << 8) | ((BiValue & 0x0000000000FF0000) << 24) | ((BiValue & 0x000000000000FF00) << 40) | ((BiValue & 0x00000000000000FF) << 56); } return liValue; } template <typename T> T transformLittleToBigEndian(const T & liValue) { unsigned short sizeCount = sizeof(T); T BiValue; if (sizeCount == 2) { BiValue |= ((liValue & 0x00FF) << 8); BiValue |= ((liValue & 0xFF00) >> 8); } else if (sizeCount == 4) { BiValue = ((liValue & 0x000000FF) << 24) | ((liValue & 0x0000FF00) << 8) | ((liValue & 0x00FF0000) >> 8) | ((liValue & 0xFF000000) >> 24); } else if (sizeCount == 8) { BiValue |= ((liValue & 0x00000000000000FF) << 56); BiValue |= ((liValue & 0x000000000000FF00) << 40); BiValue |= ((liValue & 0x0000000000FF0000) << 24); BiValue |= ((liValue & 0x00000000FF000000) << 8); BiValue |= ((liValue & 0x000000FF00000000) >> 8); BiValue |= ((liValue & 0x0000FF0000000000) >> 24); BiValue |= ((liValue & 0x00FF000000000000) >> 40); BiValue |= ((liValue & 0xFF00000000000000) >> 56); } return BiValue; }
main int ()
{
transformBigToLittleEndian ();
int value = 1;
value = transformLittleToBigEndian (value);
COUT << "value = int the large end into a small end biA =" << value << endl;
= transformBigToLittleEndian value (value);
COUT << "and then converted from the large end to the small end value =" value << << endl;
}
How to judge their own computer storage memory is big-endian or little-endian storage: https://www.cnblogs.com/azbane/p/11303463.html