Convert bool to f32 and f64

Hello,

For a project I am working on, I need to convert from bool to f32 and f64.
There are lossless conversions, from true to 1.0 and false to 0.0 - I think?

I can convert from bool to f64 by converting to i32 first.

Why is there no direct way to convert from bool to f32 or f64?

Thanks!

You can use an if expression:

fn to_f32(x: bool) -> f32 {
    if x {
        1.0
    } else {
        0.0
    }
}

I guess it's because this particular conversion isn't common enough to merit a dedicated feature.

1 Like

Hey, thanks a lot for your answer. I would prefer not to write a function with an if, as it might be possible to optimize this using other instructions. What do you think?

true as u8 as f32

Note that you might want to pass -C opt-level=3 to rustc on godbolt.

2 Likes

Thank you! Why is that?

Rust depends on optimizations for a lot of abstractions to come out zero-cost. E.g. in what @frewsxcv linked, convert2 and convert3 are pretty different without optimizations, but compile to the same instructions with opt-level=3. I'm very much prefer convert3, so I find it very significant that it turns out the same in release mode (which is using opt-level=3).

1 Like

Thanks a lot! That sheds some light.

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.