码迷,mamicode.com
首页 > 编程语言 > 详细

IP转int的另一种高效方式 C++

时间:2021-01-25 11:07:29      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:c++   bytes   union   size   pex   rgb   特点   std   利用   

#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共用内存特点实现高效转化。运行结果如下

技术图片

IP转int的另一种高效方式 C++

标签:c++   bytes   union   size   pex   rgb   特点   std   利用   

原文地址:https://www.cnblogs.com/Kingfans/p/14316480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!