Binary Bits
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!
I'd go with writing my own bit-searching function. You start from the top, and when you hit a 1, exit:
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
// 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.
**
** [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.
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).
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement