zoukankan      html  css  js  c++  java
  • IP转int的另一种高效方式 C++

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

  • 相关阅读:
    基于antlr的表达式解析器
    ANTLR语法层的选项及动作
    Understanding ANTLR Grammar Files
    写给Git初学者的7个建议
    Top 8 Diagrams for Understanding Java
    技术面不深入
    一个初级程序员学习新技术的策略
    SoftReference,WeakReference&WeakHashMap
    探索Antlr(Antlr 3.0更新版)
    Five minute introduction to ANTLR 3
  • 原文地址:https://www.cnblogs.com/Kingfans/p/14316480.html
Copyright © 2011-2022 走看看