1

I am observing an interesting result when I typecast an output:

Here is the code snippet:

int bitSize = (int)log10(1.0*16)/log10(2.0);   //bistsize = 3  it should be 4
int temp = log10(1.0*16)/log10(2.0);           //temp = 4   

Basically I want to take log2(16) which should be 4. I think my understanding of typecasting is wrong. Any suggestions?

Thanks

Richeek
  • 2,068
  • 2
  • 29
  • 37
  • I'm assuming your code uses variables and not hard coded values :) – Tony Apr 12 '11 at 23:06
  • You say you "..want to take log2(16).." but then you call `log10(..)` or am i being thick (maths was never my strongest subject!) – Tony Apr 12 '11 at 23:09
  • @Tony: Not all compilers support `log2`. See this answer: http://stackoverflow.com/questions/758001/log2-not-found-in-my-math-h/766669#766669 – Emile Cormier Apr 12 '11 at 23:34
  • no I am not using hard coded values :) It was just for illustration – Richeek Apr 12 '11 at 23:54

2 Answers2

5

I think you are only casting the output of the first log(..) function. Put parenthesis around the entire expression:

int bitSize = (int)(log10(1.0*16)/log10(2.0));
ildjarn
  • 62,044
  • 9
  • 127
  • 211
Tony
  • 9,672
  • 3
  • 47
  • 75
5

Try:

int bitSize = static_cast<int>(log10(1.0*16)/log10(2.0));

One of the niceties of the new C++ casts is that they parenthesize the argument, so it's clear exactly what you're casting.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Ohh yeah you guys are right. The whole thing needs to be put inside bracket! I will read about static cast though. – Richeek Apr 12 '11 at 23:11