IPv4地址转换成整数 Rust

整数与IP地址间的转换_牛客题霸_牛客网

  pub fn huawei_2016_6() {
        fn binary_to_decimal(num: &str) -> Option<i64> {
            if num.len() == 0 {
                return None;
            }
            let mut sum = 0;
            let vec = num
                .chars()
                .map(|x| i64::from(x.to_digit(10).unwrap()))
                .collect::<Vec<i64>>();
            for (index, item) in vec.iter().rev().enumerate() {
                sum += i64::pow(2, index as u32) * item;
            }
            Some(sum)
        }
        pub fn input_vec_num<T>(split_by: &str) -> Vec<T>
        where
            <T as std::str::FromStr>::Err: std::fmt::Debug,
            T: std::str::FromStr,
        {
            let mut input = String::new();
            std::io::stdin().read_line(&mut input).unwrap();
            input
                .split(split_by)
                .filter(|s| !s.is_empty())
                .map(|s| s.trim().to_string())
                .map(|s| s.parse::<T>().unwrap())
                .collect::<Vec<T>>()
        }
        pub fn input_num<T>() -> T
        where
            <T as std::str::FromStr>::Err: std::fmt::Debug,
            T: std::str::FromStr,
        {
            let mut input = String::new();
            std::io::stdin().read_line(&mut input).unwrap();
            input.trim().to_string().parse::<T>().unwrap()
        }
        let ip = input_vec_num::<i64>(".");
        let num = input_num::<i64>();
        let mut ipb = String::new();
        for i in ip.iter() {
            let s = format!("{:8b}", i).replace(" ", "0");
            ipb.push_str(&s);
        }
        println!("{}", binary_to_decimal(&ipb).unwrap());
        println!(
            "{}.{}.{}.{}",
            ((num & 0xff000000) >> 24),
            ((num & 0x00ff0000) >> 16),
            ((num & 0x0000ff00) >> 8),
            ((num & 0x000000ff) >> 0),
        );
    }
    fn main(){
        huawei_2016_6();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值