News for hackers. Stuff that matters.
Re:EABitTricks.h by mywittyname on Monday December 19, 2022 @11:02AM (#34053605)

    inline uint32_t Log2(uint32_t x)
    {
     const union { float f; uint32_t i; } converter = { (float)x };
     return (converter.i >> 23) - 127;
    }
This is interesting. It looks like it's returning the (biased corrected) value of mantissa.

I'm surprised that there isn't a function supplied by the compilers or in the processor that takes an int and returns the mantissa. After all, every int -> float conversion requires this step.

Re:EABitTricks.h by electroly on Monday December 19, 2022 @11:13AM (#34053751)
Take a look at the C header <ieee754.h>. It's not on all systems but it provides a union for type punning between a double and its decomposed parts. IEEE754_DOUBLE_BIAS is provided for bias correction. The same are available for floats.

(Unfortunately, the "not on all systems" part is why I don't use it, but instead copy the union and the constant verbatim into the project if I need it.)

Re:EABitTricks.h by asveikau on Monday December 19, 2022 @01:04PM (#34055312)
I thought that type punning via union is against the standard.

I personally do not think it should be ... It's a very handy tool.

Re:EABitTricks.h by electroly on Monday December 19, 2022 @02:24PM (#34056415)
I think it may be a GNU extension to explicitly allow it, but I'm no language lawyer. This header is from glibc; it may explain why it's not available on some platforms.
Re:EABitTricks.h by saagarjha on Monday December 19, 2022 @05:21PM (#34058588)
It’s legal in C.
Re:EABitTricks.h by asveikau on Monday December 19, 2022 @07:47PM (#34060028)
I think you're right. Most of the top google results seem to be from people who can't mentally separate c and c++. So when i tried to look it up around the time of the comment, i didn't get clear answers.
Re:EABitTricks.h by 10000truths on Monday December 19, 2022 @11:16AM (#34053798)
Modern CPUs have a count-leading-zeros instruction to calculate floor(log2(x)) efficiently. GCC and clang expose this with the __builtin_clz* family of intrinsics. MSVC exposes this with _BitScanReverse.

  static inline uint64_t floor_log2(uint64_t x) {
      return 63 - __builtin_clzll(x);
  }
Re:EABitTricks.h by vinkelhake on Monday December 19, 2022 @01:08PM (#34055368)
And C++ (as of C++20) exposes this and more in the header <bit>.

https://en.cppreference.com/w/cpp/header/bit

Re:EABitTricks.h by ot on Monday December 19, 2022 @11:17AM (#34053823)
> It looks like it's returning the (biased corrected) value of mantissa.

I think you mean exponent?

Re:EABitTricks.h by mywittyname on Monday December 19, 2022 @01:44PM (#34055879)
Yes, oops.
Re:EABitTricks.h by thechao on Monday December 19, 2022 @01:13PM (#34055448)