C++ 中將 IP 地址轉換為十六進位制的程式
輸入 IP 地址值,任務是將給定的 IP 地址表示為其十六進位制等效值。
什麼是 IP 地址
IP 地址或 Internet 協議是一個唯一編號,可唯一描述連線到網路的硬體。Internet 意味著在網路上,且協議定義了連線時必須遵循的一組規則和規定。由於 IP 地址,系統才可能透過網路與另一個系統通訊。IP 有兩個版本,即 −
- IPv4(Internet 協議版本 4)
- IPv6(Internet 協議版本 6)
IP 地址表示為數字序列,形式為 −
151.101.65.121
對於此轉換,以下程式使用了為 Internet 操作建立的標頭檔案“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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP