华为oj中级 整数与IP地址之间的转换

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

的每段可以看成是一个0-255的整数,需要对IP地址进行校验

知识点 字符串,位运算
运行时间限制 10M
内存限制 128
输入
输入
1 输入IP地址
2 输入10进制型的IP地址
输出
输出
1 输出转换成10进制的IP地址
2 输出转换后的IP地址
样例输入 10.0.3.193 167969729
样例输出 167773121 10.3.3.193

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<unordered_map>
#include<fstream>
#include<sstream>
#include<queue>
#include<stack>
using namespace std;
void test1(string &s){
    unsigned long int a, b, c, d;
    string str;
    int pos;
    pos = s.find(".");
    a=stol(s.substr(0, pos))<<24;
    s = s.substr(pos + 1);
    pos = s.find(".");
    b = stol(s.substr(0, pos)) << 16;
    s = s.substr(pos + 1);
    pos = s.find(".");
    c = stol(s.substr(0, pos)) << 8;
    s = s.substr(pos + 1);
    d = stol(s);
    cout << (a + b + c + d) << endl;
}
void test2(unsigned long int &n){
    unsigned long int a, b, c, d;
    d = n & 0xff;
    c = (n >> 8) & 0xff;
    b = (n >> 16) & 0xff;
    a = (n >> 24) & 0xff;
    cout << a << "." << b << "." << c << "." << d << endl;
}
int main(){
    string s;
    unsigned long int num;
    while (cin>>s>>num){
        test1(s);
        test2(num);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值