Re: Right shift >> weird result... Why?
Victor Bazarov wrote:
Kai-Uwe Bux wrote:
Mick_fae_Glesga wrote:
Ah, OK, thanks... I was hoping it would be zero....
Well, do you know of any other way of asking 'What is the highest set
bit in this number?' does such a command exist? or do I have to
look at each bit individually?
What about:
template < typename Unsigned >
Unsigned highest_bit ( Unsigned u ) {
Unsigned result = 0;
while ( u != 0 ) {
++result;
u >>= 1;
}
return ( result );
}
#include <iostream>
int main ( void ) {
unsigned long u;
while ( std::cin >> u ) {
std::cout << u << " --> " << highest_bit(u) << '\n';
}
}
Best
Kai-Uwe Bux
Or
unsigned highest_bit(unsigned a) {
return log(a) / log(2);
}
Hm, I just don't trust floating point operations:
template < typename Unsigned >
Unsigned highest_bit_kub ( Unsigned u ) {
Unsigned result = 0;
while ( u != 0 ) {
++result;
u >>= 1;
}
return ( result );
}
#include <cmath>
template < typename Unsigned >
Unsigned highest_bit_vb ( Unsigned u ) {
return std::log(u) / std::log(2);
}
#include <iostream>
#include <iomanip>
int main ( void ) {
unsigned long u;
for ( u = 0; u < 25; ++u ) {
std::cout << std::setw(3) << u
<< " highest_bit_kub: " << highest_bit_kub(u)
<< ", highest_bit_vb: " << highest_bit_vb(u) << '\n';
}
}
Output on my machine:
0 highest_bit_kub: 0, highest_bit_vb: 0
1 highest_bit_kub: 1, highest_bit_vb: 0
2 highest_bit_kub: 2, highest_bit_vb: 1
3 highest_bit_kub: 2, highest_bit_vb: 1
4 highest_bit_kub: 3, highest_bit_vb: 2
5 highest_bit_kub: 3, highest_bit_vb: 2
6 highest_bit_kub: 3, highest_bit_vb: 2
7 highest_bit_kub: 3, highest_bit_vb: 2
8 highest_bit_kub: 4, highest_bit_vb: 2
9 highest_bit_kub: 4, highest_bit_vb: 3
10 highest_bit_kub: 4, highest_bit_vb: 3
11 highest_bit_kub: 4, highest_bit_vb: 3
12 highest_bit_kub: 4, highest_bit_vb: 3
13 highest_bit_kub: 4, highest_bit_vb: 3
14 highest_bit_kub: 4, highest_bit_vb: 3
15 highest_bit_kub: 4, highest_bit_vb: 3
16 highest_bit_kub: 5, highest_bit_vb: 4
17 highest_bit_kub: 5, highest_bit_vb: 4
18 highest_bit_kub: 5, highest_bit_vb: 4
19 highest_bit_kub: 5, highest_bit_vb: 4
20 highest_bit_kub: 5, highest_bit_vb: 4
21 highest_bit_kub: 5, highest_bit_vb: 4
22 highest_bit_kub: 5, highest_bit_vb: 4
23 highest_bit_kub: 5, highest_bit_vb: 4
24 highest_bit_kub: 5, highest_bit_vb: 4
Note in particular the lines 7,8,9 as opposed to 3,4 and 15,16.
Best
Kai-Uwe Bux