📜  将IP地址转换为十六进制的程序

📅  最后修改于: 2021-05-31 21:06:17             🧑  作者: Mango

给定一个IP地址,任务是更改等效于十六进制值的IP地址。
例子:

Input  : 127.0.0.1
Output : 0x7f000001

Input  : 172.31.0.2
Output : 0xac1f0002

解释
使用库函数将IP地址转换为十六进制值,我们使用“ arpa / inet.h”头文件。 inet_addr()函数必须将标准IPv4点分十进制表示形式的字符串转换为适合用作Internet地址的整数值。

C++
// C++ program for IP to
// hexadecimal conversion
#include 
#include 
#include 
using namespace std;
  
// function for reverse hexadecimal number
void reverse(char* str)
{
    // l for swap with index 2
    int l = 2;
    int r = strlen(str) - 2;
  
    // swap with in two-2 pair
    while (l < r) {
        swap(str[l++], str[r++]);
        swap(str[l++], str[r]);
        r = r - 3;
    }
}
  
// function to conversion and print
// the hexadecimal value
void ipToHexa(int addr)
{
    char str[15];
  
    // convert integer to string for reverse
    sprintf(str, "0x%08x", addr);
  
    // reverse for get actual hexadecimal
    // number without reverse it will
    // print 0x0100007f for 127.0.0.1
    reverse(str);
  
    // print string
    cout << str << "\n";
}
  
// Driver code
int main()
{
    // The inet_addr() function  convert  string
    // in to standard IPv4 dotted decimal notation
    int addr = inet_addr("127.0.0.1");
  
    ipToHexa(addr);
  
    return 0;
}
Outpur:-0x7f000001
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.