```Date: Mon, 25 Jun 2001 22:09:50 -0400 Reply-To: Richard DeVenezia Sender: "SAS(r) Discussion" From: Richard DeVenezia Organization: MindSpring Enterprises Subject: Re: Count the '1's in a binary number? Ya: Here is a data step that counts the number of on bits and creates a bit string data _null_; n = 13; mask = 8000x; nBitsOn = 0; length bitString \$32; * left side msb; strIndex = 1; do while (mask ne 0); if band (n, mask) ne 0 then do; nBitsOn ++ 1; subStr (bitString, strIndex) = '1'; end; else subStr (bitString, strIndex) = '0'; mask = brshift ( mask, 1 ); strIndex ++ 1; end; put n= nBitsOn= bitString=; run; -- Richard DeVenezia - SAS Macros and AF Tools http://www.devenezia.com "Droogendyk, Harry" wrote in message news:F0161D3F7AC5D411A5BE009027E774D6014E8ECF@GEMMRD-SCC013EU... > Not one line, but it does as you want. > > data _null_; > > number = 13; > power = 9999999; > cnt = 0; > do while ( number > 0 and power > 0); > cnt ++ 1; > power = int(log2(number)); > number = number - ( 2 ** power ); > end; > put cnt=; > run; > > -----Original Message----- > From: Huang, Ya [mailto:ya.huang@AGOURON.COM] > Sent: June 25, 2001 5:15 PM > To: SAS-L@LISTSERV.UGA.EDU > Subject: Count the '1's in a binary number? > > > > Hi there, > > Suppose I have a positive integer number and I want to count the number of > '1's in the number presented with a binary format, for example, 13 is > '1101' in binary, so the number of '1's = 3. I wonder if there is a way > I can count it without first converting to character string then use > compress() etc.? In other word, I need a pure mathematical algorithm, better > > to be a one line solution. My instinct says that should be not very > difficult, > but I can't figure it out at the moment. > > Thanks > > Ya Huang ```

Back to: Top of message | Previous page | Main SAS-L page