首页 > 试题广场 >

整数与IP地址间的转换

[编程题]整数与IP地址间的转换
  • 热度指数:206441 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
一个长整数。
举例:一个ip地址为10.0.3.193
每段数字             相对应的二进制数
10                   00001010
0                    00000000
3                    00000011
193                  11000001

组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。

数据范围:保证输入的是合法的 IP 序列



输入描述:

输入 
1 输入IP地址
2 输入10进制型的IP地址



输出描述:

输出
1 输出转换成10进制的IP地址
2 输出转换后的IP地址

示例1

输入

10.0.3.193
167969729

输出

167773121
10.3.3.193
感觉不难,但是却花了很多时间,还是语法不熟
不能用Integer,要用Long,反正函数都有对应的
import java.util.Scanner;

public class Main{
    public static String fillZero(String str){
        int n;
        if(str.length()%8==0) n=0;
        else n = 8 - str.length()%8;
        StringBuilder zero = new StringBuilder();
        for(int i=0; i<n; i++) zero.append("0");
        return zero.toString() + str;
    }
    public static long decoding(String decode){
        String[] arr = decode.split("\\.");
        StringBuilder res = new StringBuilder();
        for(int i=0; i<arr.length; i++){
            long a = Long.parseLong(arr[i]);
            res.append(fillZero(Long.toBinaryString(a)));
        }
        return Long.parseLong(res.toString(), 2);
    }
    
    public static String encoding(long encode){
        String str = Long.toBinaryString(encode);
        str = fillZero(str);
        StringBuilder res = new StringBuilder();
        for(int i=0; i<4; i++){
            String a = str.substring(i*8, (i+1)*8);
            res.append(Long.parseLong(a, 2));
            if(i!=3)res.append(".");
        }
        return res.toString();
    }
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String decode = sc.nextLine(); // 转十进制
        long encode = sc.nextLong(); // 转IP地址
        System.out.println(decoding(decode));
        System.out.println(encoding(encode));
    }
}

发表于 2022-04-24 22:39:22 回复(0)
#include <stdio.h>
int main()
{
    unsigned int ip1,ip2,ip3,ip4,ip;
    while(scanf("%d.%d.%d.%d\n%d",&ip1,&ip2,&ip3,&ip4,&ip) != EOF)
    {
        printf("%u\n",(ip1 << 24)+(ip2 << 16)+(ip3 << 8)+ip4);
        printf("%d.%d.%d.%d\n",(ip & 0xFF000000)>>24,(ip & 0x00FF0000)>>16,(ip & 0x0000FF00)>>8,ip & 0x000000FF);
    }
    return 0;
}
发表于 2021-12-17 14:37:53 回复(0)
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str1 = sc.next();
            long str2 = sc.nextLong();
            //IP转十进制数
            String result1 = "";
            String[] strArray = str1.split("\\.");
            for(int i = 0; i < strArray.length;i++){
                int num = Integer.parseInt(strArray[i]);
                String binary = Integer.toBinaryString(num);
                while(binary.length() < 8){
                    binary = "0"+binary;
                }
                result1 += binary;
            }
            

            System.out.println(Long.parseLong(result1,2));
            //十进制数转IP
            String ip = Long.toBinaryString(str2);
            while(ip.length() < 32){
                ip = "0"+ip;
            }
            String result2 = "";
            for(int i = 0; i < 4; i++){
                String str = ip.substring(0,8);
                ip = ip.substring(8);
                int x = Integer.parseInt(str,2);
                result2 += x;
                if(i < 3){
                    result2 += ".";
                }
            }
            System.out.println(result2);
        }
    }
}

发表于 2021-11-29 00:09:58 回复(0)
唯一注意点:测试数据过大,需要用long来接受数据
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            // ip转整数
            String[] arr = sc.next().split("\\.");
            String res ="";
            for (String s : arr) {
                res += octToBin(Integer.parseInt(s), 8);
            }
            System.out.println(binToOct(res));
            // 整数转ip
            String bin = octToBin(sc.nextLong(), 32);
            res = "";
            for (int i=0; i<32; i+=8) {
                res += binToOct(bin.substring(i, i+8));
                if (i != 24) {
                    res += ".";
                }
            }
            System.out.println(res);
        }
    }

    // 十进制转二进制
    public static String octToBin(long num, int size) {
        String result = "";
        while (num != 0) {
            result = num % 2 + result;
            num = num / 2;
        }
        return zeroFormat(result, size);
    }

    // 二进制转十进制
    public static long binToOct(String str) {
        long num = 0;
        int pow = 0;
        for (int i=str.length()-1; i >= 0; i--) {
            num += (str.charAt(i)-48) * Math.pow(2, pow);
            pow ++;
        }
        return num;
    }

    // 补零
    public static String zeroFormat(String str, int size) {
        int len = str.length();
        for (int i=0; i<size-len; i++) {
            str = "0" + str;
        }
        return str;
    }
}


发表于 2021-11-07 16:09:36 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        while(input.hasNext()){
            String s = input.nextLine();
            if(s==null || s.equals("")){
                break;
            }
            if(s.contains(".")){
                String s1 = s;
                StringBuilder sb = new StringBuilder("");
            for(String ss : s1.split("\\.")){
                String sss = Integer.toBinaryString(Integer.valueOf(ss));
                int x = 8 - sss.length();
                if(x > 0){
                    for(int p = 0;p<x;p++){
                        sss = "0" + sss;
                    }
                }
                sb.append(sss);
            }
            String ipString = sb.toString();
            System.out.println(method(ipString));
            }else{
                 Long s2 = Long.valueOf(s);
            String twoS = Long.toBinaryString(s2);
            int x = 32 - twoS.length();
                if(x > 0){
                    for(int p = 0;p<x;p++){
                        twoS = "0" + twoS;
                    }
                }
            String one = twoS.substring(0,8);
            String two = twoS.substring(8,16);
            String three = twoS.substring(16,24);
            String four = twoS.substring(24,32);
            System.out.println(String.format("%d.%d.%d.%d",method(one),method(two),method(three),method(four)));
            }
        }
    }
    
    public static Long method(String s){
         Long u = 1l;
            Long num = 0l;
            for(int i = s.length() - 1; i >= 0 ; i--){
                Long ii = Long.parseLong(String.valueOf(s.charAt(i)));
                if(ii == 1l){
                    num += u;
                }
                u = u * 2;
            }
        return num;
    }
}
要记得使用Long
发表于 2021-11-01 01:57:34 回复(0)

while True:
    try:
        dot_decs_str = input()
        dec_str = input()
    except:
        break
    decs = list(map(int,dot_decs_str.split('.')))
    bins = list(map(bin,decs))
    bin_str = ''
    for i,single_bin in enumerate(bins):
        single_bin = single_bin[2:].rjust(8,'0')
        bins[i] = single_bin
    bin_str = bin_str.join(bins)
    # print(bin_str)
    dec_out_str = str(int(bin_str,2))
    print(dec_out_str)

    
    bin_str = bin(int(dec_str))[2:].rjust(32,'0')
    # print(bin_str)
    bins = []
    for i in range(4):
        bins.append(bin_str[i*8:(i+1)*8])
        # print(bins[i])
    decs = []
    for single_bin in bins:
        decs.append(str(int(single_bin,2)))
    dot_decs_str = '.'.join(decs)
    print(dot_decs_str)

    
发表于 2021-10-26 08:37:59 回复(0)
C++,欢迎修改
运行时间:3ms超过50.95% 用C++提交的代码
占用内存:480KB超过63.57%用C++提交的代码
#include<bits/stdc++.h>
using namespace std;
int main(){
    string a;
    long b;
    while(cin>>a){
        cin>>b;
       long sum = 0;
       istringstream si(a);
       while(getline(si,a,'.')){//每一个数字部分分离出来
           sum=(sum<<8)+stoi(a);
       }
        cout<<sum<<endl;
        //数字转ip
        stack<string> st;
        int t,n=4;
       while(b){
            t = (b&255);
            st.push(to_string(t));
           b = b>>8;
       }
        int i=0;
       while(!st.empty()){
           cout<<st.top();
           st.pop();
           if(i<3) // 控制“.”的打印
            cout<<".";
           i++;
       }
        cout<<endl;
    }
}




发表于 2021-08-16 19:49:59 回复(0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char input[1000];
    int i,j;
    while(scanf("%s",input)!=EOF)
    {
        int a[100]={0};
        int temp=0;
        int len=strlen(input);
        int count=0;
        for(i=0;i<len;i++)
        {
            if(input[i]!='.')
            {
                temp=temp*10+input[i]-'0';
            }
            else
            {
                a[count++]=temp;
                temp=0;
            }
        }
        a[count]=temp;
        count++;
        int int_result=0;
        for(i=0;i<count;i++)
        {
            int_result=int_result*256+a[i];
        }
        printf("%ld\n",int_result);
        long int_input;
        scanf("%ld",&int_input);
        count=0;
        while(int_input!=0)
        {
            a[count++]=int_input%256;
            int_input=int_input/256;
        }
        for(i=count-1;i>=1;i--)
        {
            printf("%d.",a[i]);
        }
        printf("%d\n",a[0]);
    }
    return 0;
}

发表于 2021-07-15 19:13:42 回复(0)
#include<iostream>
#include<stdio.h>
#include<string>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<vector>
using namespace std;
int main()
{
    long long n;
    int x;
    while(cin>>x) {
        n=x;
        for(int i=0;i<3;++i) {
            n<<=8;
            getchar(); //获取掉后面的.
            cin>>x;
            n|=x;
        }
        cout<<n<<endl;
        cin>>n; //十进制的ip
        vector<int> ip;
        int div=(1<<8)-1; //连续8个1,用于分段获取
        for(int i=0;i<4;++i) {
            int tem=(n& div);
            n>>=8;
            ip.push_back(tem);
        }
        for(int i=3;i>0;--i) {
            cout<<ip[i]<<".";
        }
        cout<<ip[0]<<endl;
    }
    return 0;
}

发表于 2021-06-26 11:24:57 回复(0)
import java.util.*;

//虽然ip地址存储占四个字节,但是int是有符号的,而ip地址转换为整数时,
//是不考虑符号的,当最高位为1时便超过了int的表示范围,因此要用long类型,而不能用int。
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String s=sc.nextLine();
            long ip=Long.parseLong(sc.nextLine());
            long res1=toHexIP(s);
            String res2=toBinaryIP(ip);
            System.out.println(res1);
            System.out.println(res2);
        }
    }
    public static long toHexIP(String s){
        String[] tmp1=s.split("\\.");
        int[] tmp2=new int[4];
        for(int i=0;i<4;i++){
            tmp2[i]=Integer.parseInt(tmp1[i]);
        }
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<4;i++){
            int num=tmp2[i];
            for(int j=0;j<8;j++){
                if(num>=Math.pow(2,8-1-j)){
                    sb.append("1");
                    num-=Math.pow(2,8-1-j);
                }
                else sb.append("0");
            }
        }
        return Long.parseLong(sb.toString(),2);
    }
    public static String toBinaryIP(long ip){
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<32;i++){
            if(ip>=Math.pow(2,32-1-i)){
                sb.append("1");
                ip-=Math.pow(2,32-1-i);
                }
            else sb.append("0");
        }
        String tmp=sb.toString();
        String s1=tmp.substring(0,8);
        String s2=tmp.substring(8,16);
        String s3=tmp.substring(16,24);
        String s4=tmp.substring(24);
        sb=new StringBuilder();
        sb.append(Integer.parseInt(s1,2)).append(".")
            .append(Integer.parseInt(s2,2)).append(".")
            .append(Integer.parseInt(s3,2)).append(".")
            .append(Integer.parseInt(s4,2));
        return sb.toString();
    }
}
发表于 2021-05-24 16:20:10 回复(0)
python写这个题还是挺快的
(1) ip地址转数字:直接对四个数字求8位的二进制串(不足8位的在前面补0),拼接起来再转十进制即可。
(2) 数字转ip:对输入的数字转二进制串,然后在前面补0到32位,再8位一组将01串转成十进制数,用点连接起来。
while True:
    try:
        print(int(''.join([bin(int(item))[2:].rjust(8, '0') for item in input().strip().split('.')]), 2))
        binstr = bin(int(input().strip()))[2:].rjust(32, '0')
        ip_list = []
        for i in range(0, 32, 8):
            ip_list.append(str(int(binstr[i:i + 8], 2)))
        print('.'.join(ip_list))
    except:
        break
可以像上面的python解法一样使用内置函数将十进制数转换为二进制,也可以老老实实用除二取余法转换。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while((line = br.readLine()) != null) {
            String[] ip = line.trim().split("\\.");
            System.out.println(ip2num(ip));
            System.out.println(num2ip(Long.parseLong(br.readLine().trim())));
        }
    }
    
    private static String num2ip(long num){
        String binaryStr = num2binary(num, 32);    // 先把数字转化为32位的二进制串
        StringBuilder sb = new StringBuilder();
        // 每8个字符将二进制串转化为十进制数
        for(int i = 0; i < 32; i += 8){
            String tempStr = binaryStr.substring(i, i + 8);
            int tempInt = 0;
            for(int j = tempStr.length() - 1; j >= 0; j--)
                tempInt += Math.pow(2, tempStr.length() - 1 - j)*(tempStr.charAt(j) - '0');
            sb.append(tempInt + ".");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
    
    private static long ip2num(String[] ip) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < ip.length; i++)
            sb.append(num2binary(Long.parseLong(ip[i]), 8));      // 将数字转化为8位二进制串
        long res = 0;
        String str = sb.toString();
        for(int i = str.length() - 1; i >= 0; i--)
            res += Math.pow(2, str.length() - 1 - i)*(str.charAt(i) - '0');
        return res;
    }
    
    // 除二取余法
    private static String num2binary(long num, int bit) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        while(num > 0){
            sb.append(num % 2);
            num /= 2;
            count ++;
        }
        // 高位补0
        while(count < bit) {
            sb.append(0);
            count ++;
        }
        return sb.reverse().toString();
    }
}


编辑于 2021-03-26 09:10:20 回复(0)
import java.util.*;
public class Main{
     public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            String[] ipArr = line.split("\\.");
            if (ipArr.length != 4) {
                continue;
            }
            ipStrToInt(ipArr);
            tenToIP(scanner);
        }
    }

    private static void tenToIP(Scanner scanner) {
        long second = scanner.nextLong();
        String secondBinaryStr = Long.toBinaryString(second);
        StringBuilder secondBuilder = new StringBuilder(secondBinaryStr);
        if (secondBinaryStr.length() < 32) {
            int pullSize = 32 - secondBinaryStr.length();
            for (int i = 0; i < pullSize; i++) {
                secondBuilder.insert(0, "0");
            }
        }
        int size = secondBuilder.length() / 8;
        List<String> integerList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            String s = secondBuilder.substring(i * 8, (i + 1) * 8);
            long num = Long.valueOf(s, 2);
            integerList.add(String.valueOf(num));
        }
        System.out.println(String.join(".", integerList));
    }

    private static void ipStrToInt(String[] ipArr) {
        StringBuilder stringBuilder = new StringBuilder();
        for (String str : ipArr) {
            String binaryNum = Long.toBinaryString(Long.parseLong(str));
            if (binaryNum.length() < 8) {
                int pullLength = 8 - binaryNum.length();
                for (int i = 0; i < pullLength; i++) {
                    stringBuilder.append("0");
                }
            }
            stringBuilder.append(binaryNum);
        }
        System.out.println(Long.valueOf(stringBuilder.toString(), 2));
    }
}

发表于 2020-08-09 20:43:38 回复(0)
#int()函数不但可以将数字或字符转为整数,
#还可以将字符串按照指定的进制转换为十进制整数表示。
#如将二进制数“1111”按照二进制数转为整数(十进制表示)
#    print(int("1111",4))
#    print(int("1111",8))
#    print(int("1111",16))
#    print(int("1111",32))

while True:
    try:
        list1 = list(map(int,input().split('.')))
        s1 = int(input())
        res = ''
        for i in list1:
            res+='0'*(8-len(bin(i)[2:]))+bin(i)[2:]
        print(int(res,2))    
            
        res2 = '0'*(32-len(bin(s1)[2:]))+bin(s1)[2:]
        n1 = int(res2[0:8],2)
        n2 = int(res2[8:16],2)
        n3 = int(res2[16:24],2)
        n4 = int(res2[24:32],2)
        print(str(n1)+"."+str(n2)+"."+str(n3)+"."+str(n4))
    except:
        break
发表于 2020-07-20 00:02:24 回复(0)
import java.util.*;
public class Main {
    static long ipToInt(String a) {
        String[] s = a.split("\\.");
        long res = 0;
        for(int i=0; i < s.length; i++) {
            res = (res << 8) + Long.valueOf(s[i]);
        }
        return res;
    }
    static String intToIP(long b) {
        int[] bit = new int[32];
        for(int i=0; i < 32; i++) 
            if(((b >> i)&1) == 1) bit[i] = 1;
        int[] res = new int[4];
        for(int i=0; i < 4; i++) {
            int t = 0, k = 8*i;
            for(int j=0; j < 8; j++) {
                if(bit[k+j] == 1)
                    t += (1<<j);
            }
            res[i] = t;
        }
        //System.out.println(Arrays.toString(res));
        return res[3] +"." + res[2] +"."+ res[1] +"."+ res[0];
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            String a = sc.next();
            long b = sc.nextLong();
            System.out.println(ipToInt(a));
            System.out.println(intToIP(b));
        }
    }
}
发表于 2020-07-09 20:16:50 回复(0)
#include <cstdio>
int main () {
    unsigned int ip[4], ip2;
    while (scanf("%u.%u.%u.%u%u", &ip[0], &ip[1], &ip[2], &ip[3], &ip2) != EOF) {
        printf("%u\n", (ip[0]<<24) + (ip[1]<<16) + (ip[2]<<8) + ip[3]);
        printf("%u.%u.%u.%u\n", ip2>>24, (ip2>>16)%256, (ip2>>8)%256, ip2%256);
    }
}

发表于 2020-04-10 15:00:08 回复(0)
/*Q33.整数与IP地址间的转换*/

#include <iostream>
using namespace std;
int main()
{
	//n代表输入的整形数字;四个数分别代表输入的ip地址
	long long n, a1, a2, a3, a4;
	char ch;//代表输入的IP地址中的点
	while (cin >> a1 >> ch >> a2 >> ch >> a3 >> ch >> a4)
	{
		cin >> n;
		long long res = 0;
		//采用左移运算符,把IP地址中的每一位依次向左移动24位(乘以2的24次方),16位,8位,0位。
		res = (a1 << 24) + (a2 << 16) + (a3 << 8) + a4;
		
		/*方法1*/
		a1 = (n >> 24);
	    a2 = (n >> 16)&255; //255的二进制码是11111111,这样就可以只保留最后8位的数字,而把前面的都变为000000000
	    a3 = (n >> 8)&255;
		a4 = n & 255;

	    /*方法2*/
		//0xff000000等代表的是16进制数,转化为二进制数为下行:
		//0xff000000 = 11111111 00000000 00000000 00000000
		//0x00ff0000 = 00000000 11111111 00000000 00000000
		//0x0000ff00 = 00000000 00000000 11111111 00000000
		//0x000000ff = 00000000 00000000 00000000 11111111
		//先按地址位取“与”运算,然后再进行右移运算,就可以排除不想要的位数
		/*a1 = ((n & 0xff000000) >> 24);
		a2 = ((n & 0x00ff0000) >> 16);
		a3 = ((n & 0x00000ff00) >> 8);
		a4 = (n & 0x000000ff);*/
		//cout << res << endl << a1 << '.' << a2 << '.' << a3 << '.' << a4 << endl;
	}
	return 0;
}

发表于 2020-03-30 10:28:50 回复(0)
C++中位运算的使用方法 - a1351937368的博客 - CSDN博客  https://blog.csdn.net/a1351937368/article/details/77746574/
知识点:
1.位逻辑运算符:&(与),|(或),~(非),^(异或);
2.移位运算符:>>(右移),<<(右移)

C++代码实现:
#include<iostream>
using namespace std;
int main()
{
    long int a1,a2,a3,a4,num;
    char c1,c2,c3;
    while(cin>>a1>>c1>>a2>>c2>>a3>>c3>>a4>>num){
        long long sum=0;
        sum=(a1<<24)+(a2<<16)+(a3<<8)+a4;
        a1=num>>24;
        a2=(num>>16)&(0x00ff);
        a3=(num>>8)&(0x0000ff);
        a4=(num)&(0x000000ff);
        cout<<sum<<endl<<a1<<"."<<a2<<"."<<a3<<"."<<a4<<endl;
    }
    return 0;
}
发表于 2019-10-05 17:08:00 回复(0)
#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
#include<vector>
using namespace std;

string itos(long long num)  //整数->字符串
{
    stringstream ss;
    ss << num;
    string s1 = ss.str();
    return s1;
}
long long stoii(string tmp)
{
    stringstream ss;
    ss << tmp;
    long long n;
    ss >> n;
    return n;
}

bool checkIP(string str_IP) //检测2进制合法性
{
    stringstream ss(str_IP);
    string str;
    int sum = 0;
    long long temp;

    while (getline(ss, str, '.'))
    {
        if (!str.size()) return false;
        else
        {
            temp = stoii(str);
            if (temp < 0 || temp>255) return false;
            else { sum++; }
        }

    }
    if (sum == 4) { return true; }
    else return false;
}

string IP_Binary_split(string str_IP) //2进制按 . 分割
{
    stringstream ss(str_IP);
    string str;
    string result;
    while (getline(ss, str, '.'))
    {
        int temp = stoii(str);
        string s1;
        while (temp)
        {
            int a = temp % 2;
            s1 += itos(a);
            temp /= 2;
        }
        if (s1.length() < 8)
        {
            int len = 8 - s1.length();
            while (len--)
            {
                s1 += '0';
            }
        }
        reverse(s1.begin(), s1.end());
        result += s1;
        s1.clear();
    }
    return result;
}

long long BinaryToTen(string str)  //2->10
{
    long long sum = 0;
    long long temp = 1;

    for (int i = 0; i < 32; ++i)
    {
        for (int j = i; j < 31; ++j)
        {
            temp *= 2;
        }
        sum += temp*(str[i] - '0');
        temp = 1;
    }
    return sum;
}

bool check_10(string str_10)
{
    long long temp = stoii(str_10);
    if (temp >4294967295 || temp<0)  return false;
    else                             return true;
}

string TenToBinary(string s)//10->2
{
    string str;
    long long temp = stoii(s);
    while (temp)
    {
        str += itos(temp % 2);
        temp /= 2;
    }
    if (str.length() % 32 != 0)
    {
        str.resize(str.length() + 32 - str.length() % 32, '0');//补全0
    }
    reverse(str.begin(), str.end());

    return str;

}

vector<string> IP_Ten_split(string str) //转化为10进制,分割,求值
{
    vector<string> result;
    vector<string> str_v;
    for (int i = 0; i < 4; ++i)
        str_v.push_back(str.substr(i * 8, 8));

    int sum = 0;
    int temp = 1;
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 8; ++j)
        {
            for (int k = j; k < 7; ++k)
            {
                temp *= 2;
            }
            sum += temp*(str_v[i][j] - '0');
            temp = 1;
        }
        result.push_back(itos(sum));
        sum = 0;
    }
    return result;
}
int main()
{
    string str_IP;
    string str_10;
    while (cin >> str_IP >> str_10)
    {
        if (checkIP(str_IP))
        {
            //cout << "s11111" << endl;
            string Binary;
            Binary = IP_Binary_split(str_IP);
            long long result = BinaryToTen(Binary);

            cout << result << endl;
        }
        if (check_10(str_10))
        {
            //cout << "s22222" << endl;
            string Ten;
            
            
            Ten = TenToBinary(str_10);
            //cout << Ten << endl;
            
            
            
            vector<string> result = IP_Ten_split(Ten);
            for (int i = 0; i < result.size() - 1; ++i)
                cout << result[i] << '.';
            if (!result.empty())
                cout << result[result.size() - 1] << endl;

        }
    }
    system("pause");
    return 0;
}

发表于 2017-09-16 19:31:52 回复(0)

//没有一楼叼
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()){
            String ip=sc.nextLine();
            String tenIp=sc.nextLine();
            getTen(ip);
            getIp(tenIp);
        }
    }
    
    public static void getTen(String ip){
        String []ipArray=ip.split("\\.");
        long sum=Long.parseLong(ipArray[0]);
        int len=ipArray.length;
        for (int i=1;i<len;i++){
            sum=sum<<8;
            sum=sum+Long.parseLong(ipArray[i]);
        }
        System.out.println(sum);
    }
    
    public static void getIp(String tenIp){
        int count=0;
        int []num=new int[4];
        long n=Long.parseLong(tenIp);
        int i=0;
        while (n!=0){
            
            if((n&1)==1){
                num[i]+=(1<<count);
            }
            n=n>>1;
            count++;
            if(count==8){
                count=0;
                i++;
            }
        }
        for (int j=3;j>0;j--){
           System.out.print(num[j]+"."); 
        }
        System.out.println(num[0]);
    }
}
发表于 2017-09-10 21:27:40 回复(0)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// 遇到的最大问题是溢出,改用long -> unsigned long 
unsigned long string2int(const string& str , int jinzhi)
{
	int size = str.size();
	unsigned long result = 0;
	for(int i = 0; i < size; i++)
	{
		result = result*jinzhi  + (str[i] - '0');
	}
	return result;
}

string int2sbin(unsigned long t,int weishu)
{
	string result = "";
	while(t != 0)  //0-255有8位
	{
		result += (t%2 + '0');
		t /= 2;
	}
	reverse(result.begin(),result.end());
	if(t == 0)
		while(result.size() < weishu)
		{
			result = '0' + result;
		}
	return result;
}

unsigned long ipto10ad(string ip)
{
    int ipsize = ip.size();
    vector<string> svec;
	string temp = "";
    for(int i = 0; i < ipsize; )
    {
        while(i < ipsize && ip[i] != '.')
		{
			temp += ip[i];
			i++;
		}
		if(ip[i] == '.' || i == ipsize)
		{
			unsigned long t = string2int(temp,10); // 把十进制表示的字符串->十进制数
			string s = int2sbin(t,8);   // 十进制数转成2进制格式
			svec.push_back(s);
			temp = "";
			i++;
		}
    }
	temp = "";
	int size = svec.size();
	for(int i = 0; i < size; i++)
	{
		temp += svec[i];
	}
	return string2int(temp,2);   // 把2进制表示的字符串->十进制数
}

 void ad10toip(const string & str2)
 {
	 // 把字符串转换成10进制数
	 unsigned long num = string2int(str2 ,10);
	 // 把十进制数转换成2进制数
	 string sbin = int2sbin(num,4*8);
	 // 以8位为分割把字符串表示的2进制数,转换成十进制数,加'.'
	 string temp = "";
	 vector<long> ivec;
	 for(int i = 0; i < 32; i++)
	 {
		if(i%8 != 0 || i == 0)
			temp += sbin[i];
		else
		{
			ivec.push_back(string2int(temp,2));
			temp ="";
			temp += sbin[i];
		}
	 }
	 ivec.push_back(string2int(temp,2)); // 最后一个没在循环里
	 int size = ivec.size();
	 for(int i = 0; i < size-1; i++)
		 cout << ivec[i] << ".";
     cout << ivec[size-1] << endl;
 }

int main()
{
    string str1;
    string str2;
    while(cin >> str1>> str2)
    {
			cout << ipto10ad(str1) << endl;
			ad10toip(str2);
		//system("pause");
        
    }
}

发表于 2017-07-04 08:56:20 回复(3)