Entry
How do you find the number of 1 bits in an integer?
Jun 7th, 2003 17:28
Sven Glazenburg, Jean-Bernard Valentaten, Allen Kolko,
I assume you want to know how to count the bits that are set (==1) in
an integer number.
You will have to write a function that returns the binary
representation of the integer as a string, then you can count the bits
that are set (the 1's in your string).
Usually integers are calculated using the two's complement (as seen
here: http://cnx.rice.edu/content/m10808/latest/), so you will have to
consider that in your function.
HTH,
Jean
-----------------------------------------------------------------
A simple function to count the 1 bits in a number (which does not
handle negative numbers (the two's complement)):
<%
function NumberOfOneBits(aNumber)
dim number, count, bit
number=0: count=0: bit=1
while number<aNumber
if (aNumber and bit)=bit then
count = count + 1
number = number + bit
end if
bit = bit * 2
wend
NumberOfOneBits = count
end function
' Try it out:
response.write NumberOfOneBits(255) & "<br>" 'This returns 8
response.write NumberOfOneBits(256) & "<br>" 'This returns 1
%>
Hope this helps,
Sven Glazenburg