peltorator

3 способа посчитать старший бит числа

Apr 17th, 2021 (edited)
204
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int f1(unsigned i) { // returns 2^(f3(i))
  2.     i |= (i >>  1);
  3.     i |= (i >>  2);
  4.     i |= (i >>  4);
  5.     i |= (i >>  8);
  6.     i |= (i >> 16);
  7.     return i - (i >> 1);
  8. }
  9.  
  10. int f2(unsigned i) { // equal to f3(i)
  11.     union { double a; unsigned b[2]; };
  12.     a = i;
  13.     return (b[1] >> 20) - 1022;
  14. }
  15.  
  16. int f3(unsigned i) {
  17.     return 32 - __builtin_clz(i);
  18. }
RAW Paste Data