1155 -- Problem of IP

本文介绍了一个简单的IP地址转换程序,该程序能够将32位二进制IP地址转换为点分十进制形式,反之亦然。通过解析二进制字符串或点分十进制字符串,实现了不同格式IP地址之间的相互转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem of IP

Time Limit:1000MS  Memory Limit:65536K
Total Submit:84 Accepted:74

Description

众所周知,计算机只能识别二进制数据,而我们却习惯十进制。所以人们发明了点分十进制来表示IP地址。即用以点分开的四个十进制数表示32位的二进制IP地址,每个数字代表IP地址中的8位。现在需要你编写程序实现二者之间的转换。

Input

输入包含多组测试数据。每组一行或为32位01字符串,或为一个点分十进制字符串。

Output

对于每一组输入,输出包含一行,为对应的另一种格式的IP地址

Sample Input

00000000000000000000000000000000
255.255.255.255

Sample Output

0.0.0.0
11111111111111111111111111111111

Source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AK1155 {
    class Program {
        static int Fun1(string s) {//2 to 10
            int n = int.Parse(s);
            int ans = 0;
            while (n > 0) {
                ans = ans * 2 + n % 10;
                n /= 10;
            }
            return ans;
        }
        static string Fun2(string s) {//10 to 2
            int n = int.Parse(s);
            int ans = 0;
            while (n > 0) {
                ans = ans * 10 + n % 2;
                n = n >> 1;
            }
            return ans.ToString();
        }
        static void Main(string[] args) {
            string s;
            while ((s = Console.ReadLine()) != null) {
                if (s.Length == 32) {//32??01??
                    string s1 = s.Substring(0 , 8);
                    Console.Write(Fun1(s1));
                    string s2 = s.Substring(8 , 8);
                    Console.Write("." + Fun1(s2));
                    string s3 = s.Substring(16 , 8);
                    Console.Write("." + Fun1(s3));
                    string s4 = s.Substring(24 , 8);
                    Console.Write("." + Fun1(s4));
                } else {//4??10??????
                    string[] ss = s.Split('.');
                    Console.Write(Fun2(ss[0]) + Fun2(ss[1]) + Fun2(ss[2]) + Fun2(ss[3]));
                }
                Console.WriteLine();
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值