C/C++ ip地址與int類型的轉換實例詳解
C/C++ ip地址與int類型的轉換實例詳解
前言
最近看道一個面試題目,大體意思就是將ip地址,例如“192.168.1.116”轉換成int類型,同時還能在轉換回去
思路
ip地址轉int類型,例如ip為“192.168.1.116”,相當于“.“將ip地址分為了4部分,各部分對應的權值為256^3, 256^2, 256, 1,相成即可
int類型轉ip地址,思路類似,除以權值即可,但是有部分字符串的操作
實現(xiàn)代碼
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define LEN 16 typedef unsigned int uint; /** * 字符串轉整形 */ uint ipTint(char *ipstr) { if (ipstr == NULL) return 0; char *token; uint i = 3, total = 0, cur; token = strtok(ipstr, "."); while (token != NULL) { cur = atoi(token); if (cur >= 0 && cur <= 255) { total += cur * pow(256, i); } i --; token = strtok(NULL, "."); } return total; } /** * 逆置字符串 */ void swapStr(char *str, int begin, int end) { int i, j; for (i = begin, j = end; i <= j; i ++, j --) { if (str[i] != str[j]) { str[i] = str[i] ^ str[j]; str[j] = str[i] ^ str[j]; str[i] = str[i] ^ str[j]; } } } /** * 整形轉ip字符串 */ char* ipTstr(uint ipint) { char *new = (char *)malloc(LEN); memset(new, '\0', LEN); new[0] = '.'; char token[4]; int bt, ed, len, cur; while (ipint) { cur = ipint % 256; sprintf(token, "%d", cur); strcat(new, token); ipint /= 256; if (ipint) strcat(new, "."); } len = strlen(new); swapStr(new, 0, len - 1); for (bt = ed = 0; ed < len;) { while (ed < len && new[ed] != '.') { ed ++; } swapStr(new, bt, ed - 1); ed += 1; bt = ed; } new[len - 1] = '\0'; return new; } int main(void) { char ipstr[LEN], *new; uint ipint; while (scanf("%s", ipstr) != EOF) { ipint = ipTint(ipstr); printf("%u\n", ipint); new = ipTstr(ipint); printf("%s\n", new); } return 0; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
上一篇:C語言實現(xiàn)大數(shù)據文件的內存映射機制
欄 目:C語言
下一篇:C語言實現(xiàn)txt數(shù)據讀入內存/CPU緩存實例詳解
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/1857.html
您可能感興趣的文章


閱讀排行
本欄相關
- 04-02c語言函數(shù)調用后清空內存 c語言調用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調用函數(shù)求fibo C語言調用函數(shù)求
隨機閱讀
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-10delphi制作wav文件的方法
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10C#中split用法實例總結
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 01-11ajax實現(xiàn)頁面的局部加載
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改