# "Convert" f64 to u64

Hi,
I would like to know how I can "convert" (or re-map) a f64 to u64 in rust.
I am trying to translate my C code below to Rust :

uint64_t flip(double d) {
union {double d; uint64_t u64;} u;
u.d = d;
return u.u64 ^ (-(u.u64 >> 63) | 0x8000000000000000ULL);
}


In Julia for example, I would do something like:

function flip(x::Float64)
y = reinterpret(UInt64, x)
y ⊻ (-(y >> 63) | 0x8000000000000000)
end


I am looking for the fastest way to do the above.
Thank you.

Looks like f64::to_bits() does what you want.

4 Likes

Thank you for the feedback.
is this the correct way to write this function in rust?

fn flip(x: f64) -> u64 {
let y: u64 = x.to_bits();
return y ^ ((-((y >> 63) as i64) as u64 | 0x8000000000000000_u64) as u64);
}


You can negate u64 without as by 0.wrapping_sub(y >> 63). It shouldn't affect performance but arguably it's more readable IMO.

3 Likes

You can use an arithmetic right shift by 63 to make a mask that is all ones (resp. all zeros) if x is negative (resp. nonnegative). Use the signed_shr method from the num crate.

Do you have an example please? sorry I am very new to Rust.

Here is an example:

1 Like

thank you @user16251

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.