Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crash while trying to do bit shift

Tags:

rust

I am trying to run this rust code

use std::net::Ipv4Addr;

fn ip_to_int(addr: Ipv4Addr) -> u32 {
        let ip = addr.octets();
        (ip[0] as u32) << 24 + (ip[1] as u32) << 16 + (ip[2] as u32) << 8 + (ip[3] as u32)
    }

fn main() {
    let ip = Ipv4Addr::new(74, 125, 227, 0);
    println!("{}", ip_to_int(ip));
}

This crashes with

thread '<main>' panicked at 'shift operation overflowed', test.rs:5

I did typecast everything to 32 bit ints and no shift is larger than 32 bits. Why does it crash? Also, isn't the compiler supposed to catch this and prevent compilation?

Abhishek@Abhisheks-MacBook-Pro-2:~$ rustc --version
rustc 1.1.0-nightly (21f278a68 2015-04-23) (built 2015-04-24)
like image 628
Abhishek Chanda Avatar asked Apr 09 '26 08:04

Abhishek Chanda


1 Answers

According to the the Rust reference, operator + as a stronger precedence than operator <<, meaning that your expression is actually parsed like this:

(ip[0] as u32) << (24 + (ip[1] as u32)) << (16 + (ip[2] as u32)) << (8 + (ip[3] as u32))

Which can pretty easily overflow.

You need to add the appropriates brackets:

((ip[0] as u32) << 24) + ((ip[1] as u32) << 16) + ((ip[2] as u32) << 8) + (ip[3] as u32)
like image 113
Levans Avatar answered Apr 11 '26 23:04

Levans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!