Binary Bits

Started by
5 comments, last by shuks 22 years, 4 months ago
This is my first post on Gamedev. I would like to know if there is away of geting the number of binary bits used to represent a decimal number using the log() and log10(). e.g you need 3 bits to represent the number 6. Is there a way of using the above functions? Please help me out!
Advertisement
I'd go with writing my own bit-searching function. You start from the top, and when you hit a 1, exit:

      // 32 bits searchingint value = inputValue;if (!value) return 0;int temp = value;int count = 0;while (!(temp & 0x80000000)) { temp <<= 1; count++;}return 32 - count;      


This is only a little code-snippet I wrote in a few seconds or so, so pleaz don't go on laughing for any bugs or alike. Try make optimizations yourself...

Edited by - coelurus on December 13, 2001 3:55:46 PM

Edited by - coelurus on December 13, 2001 3:56:25 PM
/*
**
** [func] - bitcount.
** [desc] - returns the number of bits required to hold a value.
** [entr] - int value; the value.
** [exit] - int; the number of bits required to hold a value.
**
*/
int bitcount(int value) {
int cmp = 2, retval = 0;

for (int count=1; count <= 32; count++) {
if ((cmp - 1) >= value) {
retval = count;
count = 32;
}
else cmp *= 2;
}
return (retval);
}

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
Bits are always binary; the term "bit" comes from "binary digit."
quote:Original post by merlin9x9
Bits are always binary; the term "bit" comes from "binary digit."


Not when you''re doing Information and Signal Theory (bit = binary unit).

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
quote:Original post by shuks
I would like to know if there is away of geting the number of binary bits used to represent a decimal number using the log() and log10(). e.g you need 3 bits to represent the number 6. Is there a way of using the above functions?


Here''s hoping it''s not for a homework assignment...

But I think the answer you''re looking for is:

  int countBits( int value ){   assert( value != 0 );   return( (int)( log10( value ) / log10( 2 ) ) + 1 );}  


(and here''s hoping my math skills are still what they were)

Cheers,
-scott
Thanks guys!
The code snippets really helped. I knew how to obtain the number of bits.

I would like to thank scott for his solution. It was what i wanted.
By the way, your math skills are excellent.
Thanks everyone.

This topic is closed to new replies.

Advertisement