Rust: f64 as usize -- different result on 64 bit os and 32 bit os.

Created on 26 Apr 2018  路  4Comments  路  Source: rust-lang/rust

Here is an example code:

fn main() {
    let x: f64 = -100.;
    println!("f64: {}", x);
    println!("isize: {}", x as isize);
    println!("usize: {}", x as usize);
    println!("isize usize {}", x as isize as usize);
}

$ rustc -O example.rs

On 64 bit system (x86_64):
f64: -100
isize: -100
usize: 18446744073709551516 <--- 2 rows is equal, Ok.
isize usize 18446744073709551516 <--- 2 rows is equal, Ok.

On 32 bit system (Raspberry Pi3):
f64: -100
isize: -100
usize: 0 <--- why not equal this 2 rows?
isize usize 4294967196 <--- why not equal this 2 rows?

C-bug T-compiler

Most helpful comment

This is probably just #10184. Currently casting -100. to any unsigned int is Undefined Behaviour.

All 4 comments

Interestingly, on the playpen with u64 and u32 types you get:

f64: -100

i32: -100
u32: 4294967196
i32 -> u32 4294967196

i64: -100
u64: 18446744073709551516
i64 -> u64 18446744073709551516

https://play.rust-lang.org/?gist=d6e2a566cb926ee6ebdcd84c53610183&version=stable&mode=debug

Your code running good on x86_64, but on 32 bit OS (Raspberry Pi3):

f64: -100

i32: -100
u32: 0
i32 -> u32 4294967196

i64: -100
u64: 0
i64 -> u64 18446744073709551516

This is probably just #10184. Currently casting -100. to any unsigned int is Undefined Behaviour.

Was this page helpful?
0 / 5 - 0 ratings