Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to work on the actual bitwise representation of a floating point number, you should do something like this:</p> <pre><code>float f; /* whatever your float is */ int i = *(int *)&amp;f; </code></pre> <p>What this does is take the address of <code>f</code> with the address-of operator, <code>&amp;</code>. This address is of type <code>float *</code>, a pointer to a float. Then it recasts it with <code>(int *)</code>, which says "pretend this pointer doesn't point to a <code>float</code> anymore, but now it points to an <code>int</code>". Note that it doesn't change the value at <code>f</code> at all. Then the last <code>*</code> (or first, since we read right-to-left) dereferences this pointer, which is a pointer to an <code>int</code>, and therefore returns an <code>int</code>, a.k.a. the integer with the same bitwise representation as the float.</p> <p>To do the opposite (convert and <code>int i</code> back to a <code>float f</code>), do the opposite:</p> <pre><code>f = *(float *)&amp;i; </code></pre> <p>Unless I am mistaken, this operation is undefined by the C standard, but will probably work on most computers and compilers. It is undefined because I believe the actual floating-point representation of numbers is implementation-dependent, and can be left to the CPU or the compiler, and therefore the value of <code>i</code> is almost impossible to predict after this operation (same goes for the value of <code>f</code> in the reverse operation). It is famously used in John Carmack's inverse square root function for the same nefarious purpose.</p> <p>Anyway, if you're doing this in real code, you should probably stop and think twice about what you're trying to do and why you're using <code>float</code>s to do it. However, if you're just doing this out of curiosity, or you have thought about these and are sure of your design and methods, go for it.</p> <p>I'm led to believe that you already know how to count the number of bits set in a regular integer, as this is a much easier task. If you don't know, your compiler (or the C language, I don't even know) may have a function to count bits, or you could use something from the wonderful <a href="http://graphics.stanford.edu/~seander/bithacks.html" rel="nofollow noreferrer">Bit-Twiddling Hacks</a> website, which has ways to do things like this with bitwise operations (which should be pretty fast).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload