Interesting Macro (without branch or compares) to Increment And Decrement Wrapping Values

For processors where compare and branch is very expensive, to use in critical code:


#define DECL_WRAP_INC( type_name, type, stype, bit_mask )                                
static inline type wrap_inc_##type_name( const type val, const type min, const type max )
{                                                                                        
  const type result_inc   = val + 1;                                                      
  const type max_diff     = max - val;                                                    
  const type max_diff_nz  = (type)( (stype)( max_diff | -max_diff ) >> bit_mask );        
  const type max_diff_eqz = ~max_diff_nz;                                                
  const type result       = ( result_inc & max_diff_nz ) | ( min & max_diff_eqz );        
                                                                                         
  return (result);
}

From http://cellperformance.beyond3d.com/articles/2006/07/increment-and-decrement-wrapping-values.html#more

Comentarios

Entradas populares