c - Casting unsigned int to unsigned short int with bit operator -


i cast unsigned int (32bit) unsigned short int (16bit) b in following way:

  • if <= 2^16-1 b=a
  • if > 2^16-1 b=2^16-1

in other words cast if > of maximum allowed value 16bit set max value.

how can achieved bit operations or other non branching method?

find minimum of 2 integers without branching:

http://graphics.stanford.edu/~seander/bithacks.html#integerminormax

on rare machines branching expensive , no condition move instructions exist, above expression might faster obvious approach, r = (x < y) ? x : y, though involves 2 more instructions. (typically, obvious approach best, though.)

just kick things off, here's brain-dead benchmark. i'm trying 50/50 mix of large , small values "at random":

#include <iostream> #include <stdint.h>  int main() {     uint32_t total = 0;     uint32_t n = 27465;     (int = 0; < 1000*1000*500; ++i) {         n *= 30029; // worst prng in world         uint32_t = n & 0x1ffff;         #ifdef empty             uint16_t b = a; // gives wrong total, of course.         #endif         #ifdef normal             uint16_t b = (a > 0xffff) ? 0xffff : a;         #endif         #ifdef ruslik             uint16_t b = (-(a >> 16) >> 16) | a;         #endif         #ifdef bithack             uint16_t b = ^ ((0xffff ^ a) & -(0xffff < a));         #endif         total += b;     }     std::cout << total << "\n"; } 

on compiler (gcc 4.3.4 on cygwin -o3), normal wins, followed ruslik, bithack, respectively 0.3, 0.5 , 0.9 seconds slower empty loop. benchmark means nothing, haven't checked emitted code see whether compiler's smart enough outwit me somewhere. ruslik's anyway.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -