zoukankan      html  css  js  c++  java
  • 【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/


               作者:gnuhpc
               出处:http://www.cnblogs.com/gnuhpc/
               除非另有声明,本网站采用知识共享“署名 2.5 中国大陆”许可协议授权。


分享到:

查看全文
  • 相关阅读:
    java dom4j创建 ,修改 ,删除 xml文件内容
    HTML 标签权重比较
    [Operating System] {ud923} P4L4: Datacenter Technologies
    [Operating System] {ud923} P4L3: Distributed Shared Memory
    [Operating System] {ud923} P4L2: Distributed File Systems
    [Operating System] {ud923} P4L1: Remote Procedure Calls
    [Operating System] {ud923} P3L6: Virtualization
    [Operating System] {ud923} P3L5: I/O Management
    [Operating System] {ud923} P3L4: Synchronization Constructs
    [Operating System] {ud923} P3L3: Inter-Process Communication
  • 原文地址:https://www.cnblogs.com/gnuhpc/p/2316949.html
  • Copyright © 2011-2022 走看看