@@ -1226,6 +1226,45 @@ impl f32 {
12261226 pub fn atanh ( self ) -> f32 {
12271227 0.5 * ( ( 2.0 * self ) / ( 1.0 - self ) ) . ln_1p ( )
12281228 }
1229+
1230+ /// Raw transmutation to `u32`.
1231+ ///
1232+ /// Converts the `f32` into its raw memory representation,
1233+ /// similar to the `transmute` function.
1234+ ///
1235+ /// Note that this function is distinct from casting.
1236+ ///
1237+ /// ```
1238+ /// #![feature(float_bits_conv)]
1239+ /// assert!((1f32).to_bits() != 1f32 as u32); // to_bits() is not casting!
1240+ /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1241+ ///
1242+ /// ```
1243+ #[ unstable( feature = "float_bits_conv" , reason = "recently added" , issue = "0" ) ]
1244+ #[ inline]
1245+ pub fn to_bits ( self ) -> u32 {
1246+ unsafe { :: mem:: transmute ( self ) }
1247+ }
1248+
1249+ /// Raw transmutation from `u32`.
1250+ ///
1251+ /// Converts the given `u32` containing the float's raw memory
1252+ /// representation into the `f32` type, similar to the
1253+ /// `transmute` function.
1254+ ///
1255+ /// Note that this function is distinct from casting.
1256+ ///
1257+ /// ```
1258+ /// #![feature(float_bits_conv)]
1259+ /// use std::f32;
1260+ /// let difference = (f32::from_bits(0x41480000) - 12.5).abs();
1261+ /// assert!(difference <= 1e-5);
1262+ /// ```
1263+ #[ unstable( feature = "float_bits_conv" , reason = "recently added" , issue = "0" ) ]
1264+ #[ inline]
1265+ pub fn from_bits ( v : u32 ) -> Self {
1266+ unsafe { :: mem:: transmute ( v) }
1267+ }
12291268}
12301269
12311270#[ cfg( test) ]
@@ -1870,4 +1909,16 @@ mod tests {
18701909 assert_approx_eq ! ( ln_2, 2f32 . ln( ) ) ;
18711910 assert_approx_eq ! ( ln_10, 10f32 . ln( ) ) ;
18721911 }
1912+
1913+ #[ test]
1914+ fn test_float_bits_conv ( ) {
1915+ assert_eq ! ( ( 1f32 ) . to_bits( ) , 0x3f800000 ) ;
1916+ assert_eq ! ( ( 12.5f32 ) . to_bits( ) , 0x41480000 ) ;
1917+ assert_eq ! ( ( 1337f32 ) . to_bits( ) , 0x44a72000 ) ;
1918+ assert_eq ! ( ( -14.25f32 ) . to_bits( ) , 0xc1640000 ) ;
1919+ assert_approx_eq ! ( f32 :: from_bits( 0x3f800000 ) , 1.0 ) ;
1920+ assert_approx_eq ! ( f32 :: from_bits( 0x41480000 ) , 12.5 ) ;
1921+ assert_approx_eq ! ( f32 :: from_bits( 0x44a72000 ) , 1337.0 ) ;
1922+ assert_approx_eq ! ( f32 :: from_bits( 0xc1640000 ) , -14.25 ) ;
1923+ }
18731924}
0 commit comments