欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Java代碼將IP地址轉(zhuǎn)換為int類型的方法

 更新時間:2015年08月07日 10:24:56   作者:zinss26914  
這篇文章主要介紹了使用Java代碼將IP地址轉(zhuǎn)換為int類型的方法,這也是各大計算機考試和ACM以及面試的常見基礎(chǔ)問題,需要的朋友可以參考下

基本知識點 
 
IP ——> 整數(shù):
把IP地址轉(zhuǎn)化為字節(jié)數(shù)組
通過左移位(<<)、與(&)、或(|)這些操作轉(zhuǎn)為int
整數(shù) ——> IP:
將整數(shù)值進行右移位操作(>>>),右移24位,再進行與操作符(&)0xFF,得到的數(shù)字即為第一段IP。
將整數(shù)值進行右移位操作(>>>),右移16位,再進行與操作符(&)0xFF,得到的數(shù)字即為第二段IP。
將整數(shù)值進行右移位操作(>>>),右移8位,再進行與操作符(&)0xFF,得到的數(shù)字即為第三段IP。
將整數(shù)值進行與操作符(&)0xFF,得到的數(shù)字即為第四段IP。

思路
ip地址轉(zhuǎn)int類型,例如ip為“192.168.1.116”,相當于“.“將ip地址分為了4部分,各部分對應(yīng)的權(quán)值為256^3, 256^2, 256, 1,相成即可

int類型轉(zhuǎn)ip地址,思路類似,除以權(quá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)文章

最新評論