กำหนดโดยอินพุตเป็นค่าที่อยู่ IP และภารกิจคือการแสดงที่อยู่ IP ที่ระบุเป็นเลขฐานสิบหกที่เทียบเท่ากัน
ที่อยู่ IP คืออะไร
ที่อยู่ IP หรืออินเทอร์เน็ตโปรโตคอลเป็นหมายเลขเฉพาะที่อธิบายฮาร์ดแวร์ของคุณที่เชื่อมต่อกับเครือข่ายโดยเฉพาะ อินเทอร์เน็ตหมายถึงผ่านเครือข่ายและโปรโตคอลกำหนดชุดของกฎและข้อบังคับที่ต้องปฏิบัติตามสำหรับการเชื่อมต่อ เนื่องจากที่อยู่ IP เท่านั้นจึงเป็นไปได้ที่ระบบจะสื่อสารกับระบบอื่นผ่านเครือข่าย IP มีสองเวอร์ชันคือ -
- IPv4(Internet Protocol รุ่น 4)
- IPv6(Internet Protocol รุ่น 6)
ที่อยู่ IP จะแสดงเป็นลำดับของตัวเลขที่อยู่ในรูปแบบ -
151.101.65.121
สำหรับการแปลงนี้ โปรแกรมด้านล่างใช้ไฟล์ส่วนหัว “arpa/inet.h” ซึ่งสร้างขึ้นสำหรับการทำงานของอินเทอร์เน็ต
ตัวอย่าง
Input-: 127.0.0.1 Ouput-: 0x7f000001 Input-: 172.31.0.2 Output-: 0xac1f0002
อัลกอริทึม
Start
Step1-> Declare function to reverse
void reverse(char* str)
set int len = 2
set int r = strlen(str) – 2
Loop While (len < r)
call swap(str[len++], str[r++])
Call swap(str[len++], str[r])
Set r = r – 3
End
End
Step 2-> Declare function to convert IP address to hexadecimal
void convert(int ip_add)
declare char str[15]
call sprintf(str, "0x%08x", ip_add)
call reverse(str)
print str
step 3-> In main()
declare int ip_add = inet_addr("127.0.0.1")
call convert(ip_add)
Stop ตัวอย่าง
#include <arpa/inet.h>
#include <iostream>
#include <string.h>
using namespace std;
//reverse hexadecimal number
void reverse(char* str) {
int len = 2;
int r = strlen(str) - 2;
while (len < r) {
swap(str[len++], str[r++]);
swap(str[len++], str[r]);
r = r - 3;
}
}
//Convert IP address to heaxdecimal
void convert(int ip_add) {
char str[15];
sprintf(str, "0x%08x", ip_add);
reverse(str);
cout << str << "\n";
}
int main() {
int ip_add = inet_addr("127.0.0.1");
convert(ip_add);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น จะเกิดผลลัพธ์ดังต่อไปนี้
0x7f000001