Date: Mon, 25 Jun 2001 16:20:46 -0700 "Huang, Ya" "SAS(r) Discussion" "Huang, Ya" Re: Count the '1's in a binary number? To: Jens Manfredson multipart/alternative;

This is it!

I thought about using shift but forgot the mask, thanks for reminding me. Here is the shift and mask algorithm:

64 data _null_; 65 a=13; 66 cnt=0; 67 do while(a>0); 68 cnt+band(a,1); 69 put a= binary. cnt=; 70 a=brshift(a,1); 71 end; 72 run;

a=00001101 cnt=1 a=00000110 cnt=1 a=00000011 cnt=2 a=00000001 cnt=3

Thank you very much!

Regards,

Ya Huang

> -----Original Message----- > From: Jens Manfredson [mailto:HFUOQUCSVTYY@SPAMMOTEL.COM] > Sent: Monday, June 25, 2001 4:04 PM > To: SAS-L@LISTSERV.UGA.EDU > Subject: Re: Count the '1's in a binary number? > > > > 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. > > Normally you would do it with a shift operation and a mask operation. > Shift 1 right, mask with 0000001 and add. > > Jens >

[text/html]

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