#include <iostream> typedef unsigned char byte; typedef unsigned int uInt32; #if 0 // 常规方法 bool bytesToInt(uInt32& uIP, byte byIP[4]) { uIP = byIP[3] & 0xFF | (byIP[2] & 0xFF) << 8 | (byIP[1] & 0xFF) << 16 | (byIP[0] & 0xFF) << 24; return true; } bool intToBytes(uInt32 uIP, byte byIP[4]) { byIP[0] = (byte)((uIP >> 24) & 0xFF); byIP[1] = (byte)((uIP >> 16) & 0xFF); byIP[2] = (byte)((uIP >> 8) & 0xFF); byIP[3] = (byte)(uIP & 0xFF); return true; } #else // 利用联合体共用同一块内存; union IPEx { uInt32 uIP; byte byIP[4]; }; bool bytesToInt(uInt32& uIP, byte byIP[4]) { IPEx ipEx; memcpy(ipEx.byIP, byIP, 4 * sizeof(byte)); uIP = ipEx.uIP; return true; } bool intToBytes(uInt32 uIP, byte byIP[4]) { IPEx ipEx; ipEx.uIP = uIP; memcpy(byIP, ipEx.byIP, 4 * sizeof(byte)); return true; } #endif int main() { uInt32 uIP1 = 0; byte byIP1[4] = { 192,168,1,163 }; bytesToInt(uIP1, byIP1); std::cout << (int)byIP1[0] << "." << (int)byIP1[1] << "." << (int)byIP1[2] << "." << (int)byIP1[3] << " -> " << uIP1 << std::endl; uInt32 uIP2 = 3232235939; byte byIP2[4] = { 0,0,0,0 }; intToBytes(uIP2, byIP2); std::cout << uIP2 << " -> " << (int)byIP1[0] << "." << (int)byIP1[1] << "." << (int)byIP1[2] << "." << (int)byIP1[3] << std::endl; return 0; }
常规方法进行偏移运算,本文巧用C++的union共用内存特点实现高效转化。运行结果如下