【Programming Clip】點分十進制IP和長整型轉換


 作者:gnuhpc 
出處:http://www.cnblogs.com/gnuhpc/ 
 

1.用途

將一個整型數值和一個IP字符串相互轉換。

2.描述語言

C, Java

3.原理

IP地址是一個以點作為分隔符的十進制四字段字符串,例如“10.0.3.193”。將這四個十進制數轉化為二進制即為:

每段數字             相對應的二進制數
10                          00001010
0                            00000000
3                            00000011
193                       11000001

以從左到右的順序放在一起,為00001010 00000000 00000011 11000001,轉換為10進制數就是:167773121,即為一個長整型。

從長整型到字符串的轉化要點:移位、屏蔽掉不需要的位,字符串拼接。在C語言中可以使用指針巧妙的封裝移位操作。

從字符串到長整型的轉化要點:解析字符串,移位,求和。

4.代碼

C語言描述:

/*
 * =====================================================================================
 *
 *       Filename:  ipconverter.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/08/2012 11:02:12 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  gnuhpc (http://www.cnblogs.com/gnuhpc), warmbupt@gmail.com
 *        Company:  CMBC
 *
 * =====================================================================================
 */
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;


char* itoa(int i)
{
	char* temp = new char(6);
	sprintf(temp,"%d",i);
	return temp;
}

char* numToIP1(unsigned int num)
{
	char* buf = new char[sizeof("aaa.bbb.ccc.ddd")];
	unsigned char* p = (unsigned char *)&num;
	sprintf(buf, "%d.%d.%d.%d", p[3]&0xff,p[2]&0xff,p[1]&0xff,p[0]&0xff);
	return buf;
}
char* numToIP2(unsigned int num)
{
	char* buf = new char[sizeof("aaa.bbb.ccc.ddd")];
	for(int i=3;i>=0;i--)
	{
		strcat(buf, itoa((num>>8*i)&0xff));
		if(i!=0)
			strcat(buf,".");
	}

	return buf;
}

unsigned int ipToNum(char* ip)
{
	char* p;
	int sections[4]={0};
	int i=0;

	p = strtok(ip,".");
	while( p )
	{
		sections[i] = atoi(p);
		p = strtok(NULL,".");
		cout << sections[i] << endl;
		i++;
	}

	unsigned int num =0;
	for( int j=3,i=0 ; j>=0 ; j--,i++ )
	{
		num += (sections[i] <<(8*j));
	}
	
	return num;
}

int main(){
	char* p = numToIP1(167773121);
	cout << p << endl;
	delete p;

	p = numToIP2(167773121);
	cout << p << endl;
	delete p;


	char ip[16] = "10.0.3.193";
	cout << ipToNum(ip) << endl;
	return 0;
}

Java描述:

package cnblogs.gnuhpc.ipconvertor;

public class IPConvertor {
	public static String numToIP(long ip){
		StringBuilder sb = new StringBuilder();
		for (int i = 3; i >=0; i--) {
			sb.append((ip>>>(i*8))&0x000000ff);
			if (i!=0) {
				sb.append('.');
			}
		}
		System.out.println(sb);
		return sb.toString();
	}
	
	public static long ipToNum(String ip){
		long num = 0;
		String[] sections = ip.split("\\.");
		int i=3;
		for (String str : sections) {
			num+=(Long.parseLong(str)<<(i*8));
			i--;
		}
		System.out.println(num);
		return num;
	}
}

5.收獲

1)C語言中unsigned int類型為4字節,范圍為0 -> +4,294,967,295 ,而long int也為4字節,只是其從0開始,范圍為-2,147,483,648 -> +2,147,483,647 。Java中沒有unsigned類型,long類型為8 字節,范圍為 -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

2)Java中String.split方法,如果用“.”作為分隔的話,必須采用:String.split("\\."),這樣才能正確的分隔開,不能用String.split(".")。

3)Java中的位移:

  • <<是左移符號,列x<<1,就是x的內容左移一位(x的內容並不改變)
  • >>是帶符號位的右移符號,x>>1就是x的內容右移一位,如果開頭是1則補1,是0責補0,(x的內容並不改變)
  • >>>是不帶符號位的右移,x>>>1就是x的內容右移一位,開頭補0(x的內容並不改變)
  • 6.下載地址

     

    http://gnuhpc.googlecode.com/svn/trunk/ProgrammingExc/src/cnblogs/gnuhpc/ipconvertor/


    免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM