C/C++ ip地址與int類型的轉(zhuǎn)換實例詳解
C/C++ ip地址與int類型的轉(zhuǎn)換實例詳解
前言
最近看道一個面試題目,大體意思就是將ip地址,例如“192.168.1.116”轉(zhuǎn)換成int類型,同時還能在轉(zhuǎn)換回去
思路
ip地址轉(zhuǎn)int類型,例如ip為“192.168.1.116”,相當(dāng)于“.“將ip地址分為了4部分,各部分對應(yīng)的權(quán)值為256^3, 256^2, 256, 1,相成即可
int類型轉(zhuǎn)ip地址,思路類似,除以權(quán)值即可,但是有部分字符串的操作
實現(xiàn)代碼
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define LEN 16 typedef unsigned int uint; /** * 字符串轉(zhuǎn)整形 */ 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]; } } } /** * 整形轉(zhuǎn)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; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
COLORREF,COLOR,RGB,CString的轉(zhuǎn)化總結(jié)分析
實際的軟件開發(fā)過程中,常需要用到非.net平臺的代碼。這時候就可能碰到ColorRef(也就是以int類型代表的顏色值或是以DWORD值表示的顏色)。這跟.net平臺下的顏色的相互轉(zhuǎn)換MS并沒有直接實現(xiàn)2013-09-09解析在Direct2D中畫Bezier曲線的實現(xiàn)方法
本篇文章是對在Direct2D中畫Bezier曲線的實現(xiàn)方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05c語言獲取當(dāng)前工作路徑的實現(xiàn)代碼(windows/linux)
這篇文章主要介紹了c語言獲取當(dāng)前工作路徑的實現(xiàn)代碼(windows/linux),需要的朋友可以參考下2017-09-09詳談C與C++的函數(shù)聲明中省略參數(shù)的不同意義
下面小編就為大家分享一篇詳談C與C++的函數(shù)聲明中省略參數(shù)的不同意義,具有非常好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11