title: Precisly convert float 32 to unsigned short or unsigned char
body: <p>First of all sorry if this is a duplicate, I couldn't find any subject answering my question.</p>
  
  <p>I'm coding a little program that will be used to convert 32-bit floating point values to short int (16 bits) and unsigned char (8 bits) values. This is for HDR images purpose.</p>
  
  <p>From <a href="http://lol.zoy.org/blog/2011/3/20/understanding-fast-float-integer-conversions" rel="nofollow noreferrer">here</a> I could get the following function (without clamping): </p>
  
  <pre><code>static inline uint8_t u8fromfloat(float x)
  {
      return (int)(x * 255.0f);
  }
  </code></pre>
  
  <p>I suppose that in the same way we could get short int by multiplying by <code>(pow( 2,16 ) -1)</code></p>
  
  <p>But then I ended up thinking about ordered dithering and especially to Bayer dithering. To convert to uint8_t I suppose I could use a 4x4 matrix and a 8x8 matrix for unsigned short.</p>
  
  <p>I also thought of a Look-up table to speed-up the process, this way:</p>
  
  <pre><code>uint16_t LUT[0x10000] // 2¹⁶ values contained
  </code></pre>
  
  <p>and store 2^16 unsigned short values corresponding to a float.
  This same table could be then used for uint8_t as well because of the implicit cast between unsigned short ↔ unsigned int</p>
  
  <p>But wouldn't a look-up table like this be huge in memory? Also how would one fill a table like this?!</p>
  
  <p>Now I'm confused, what would be best according to you?</p>
  
  <p>EDIT after uwind answer: Let's say now that I also want to do basic color space conversion at the same time, that is before converting to U8/U16 , do a color space conversion (in float), and then shrink it to U8/U16. Wouldn't in that case use a LUT be more efficient? And yeah I would still have the problem to index the LUT.</p>