rust - Crash while trying to do bit shift -


i trying run rust code

use std::net::ipv4addr;  fn ip_to_int(addr: ipv4addr) -> u32 {         let ip = addr.octets();         (ip[0] u32) << 24 + (ip[1] u32) << 16 + (ip[2] u32) << 8 + (ip[3] u32)     }  fn main() {     let ip = ipv4addr::new(74, 125, 227, 0);     println!("{}", ip_to_int(ip)); } 

this crashes with

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

i did typecast 32 bit ints , no shift larger 32 bits. why crash? also, isn't compiler supposed catch , prevent compilation?

abhishek@abhisheks-macbook-pro-2:~$ rustc --version rustc 1.1.0-nightly (21f278a68 2015-04-23) (built 2015-04-24) 

according the rust reference, operator + stronger precedence operator <<, meaning expression parsed this:

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

which can pretty overflow.

you need add appropriates brackets:

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

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -