Program to convert IP address to hexadecimal
Given an IP Address and task is to change the IP address equivalent the hexadecimal value.
Examples:
Input : 127.0.0.1 Output : 0x7f000001 Input : 172.31.0.2 Output : 0xac1f0002
Explanation
using the Library function to convert the IP address to convert into the hexadecimal value we use ” arpa/inet.h “ header file. The inet_addr() function shall convert the string in the standard IPv4 dotted decimal notation, to an integer value suitable for use as an Internet address.
C++
// C++ program for IP to // hexadecimal conversion #include <arpa/inet.h> #include <iostream> #include <string.h> 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
Recommended Posts:
- Python program to find IP Address
- Program to Convert List to Map in Java
- Program to convert the diagonal elements of the matrix to 0
- Program to Convert a Vector to List in Java
- Program to convert Byte Array to Writer in Java
- Count Hexadecimal Number
- StringStream in C++ for Decimal to Hexadecimal and back
- Python program to convert time from 12 hour to 24 hour format
- Three address code in Compiler
- C++ program to Convert a Matrix to Sparse Matrix
- Address Resolution in DNS (Domain Name Server)
- Logical and Physical Address in Operating System
- How to convert timestamp to time ago in PHP ?
- How to convert an image to base64 encoding in PHP?
- Convert String to Double in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



