How to efficiently compute absolute value of float in #![no_std]?

56 points Derice

I am writing a #![no_std] library that at one point needs to get the absolute value of a floating point number. This seems to need the standard library though. Currently I use #[cfg(feature = ...)] conditionals to enable a custom implementation of abs when the std feature is disabled, but this compiles to longer assembly compared to the std abs: https://godbolt.org/z/jY115ebTv. Is there a way to get this code quality in #![no_std]?

EDIT: I have compiled all answers in the thread in this godbolt link: https://godbolt.org/z/9nEEMofEG.

EDIT: Same code on the rust playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=02e74329c1fcc999e55f850c0544528b.

FINAL EDIT: For those who do not wish to read the whole thread, the code I ended up using is a combination of the comment by /u/boomshroom and notes by /u/matthieum:

fn abs(x: f64) -> f64 {
    f64::from_bits(x.to_bits() & !(1 << 63))
}