使用bitset和string的组合实现整数和ip地址的转换

整数与IP地址间的转换

http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    for (char& c : s) {
        if (c == '.') c = ' ';
    }
    istringstream strm(s);
    string str;
    unsigned k;
    for (int i = 0; i < 4; ++i) {
        strm >> k;
        str += bitset<8>(k).to_string();
    }
    k = bitset<32>(str).to_ulong();
    cout << k << endl;
    
    cin >> k;
    str = bitset<32>(k).to_string();
    for (int i = 0; i < 4; ++i) {
        cout << bitset<8>(str.substr(8 * i, 8)).to_ulong();
        if (i != 3) cout << ".";
    }
    cout << endl;
    
    
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务