g | x | w | all
Bytes Lang Time Link
041C# 8241010T094932ZModo 6.6
0108051 opcode241009T051537Zl4m2
025Zsh230530T042818Zroblogic
002Thunno 2 S230610T161535ZThe Thon
005BitCycle220516T153843ZRomanp
028SMALL220516T151815Zstefvans
007K ngn/k220508T001957Zoeuf
0138051 Machine Code220506T125122ZElcan
038Desmos220506T033512ZnaffetS
019JavaScript220427T220810ZMatthew
013PARI/GP190420T100222Zalephalp
013Python 3.10+220424T024133ZnaffetS
009Factor220424T015943Zchunes
002Vyxal220424T014801ZnaffetS
026Python220205T134850ZOliver
015Rust210409T080030ZBubbler
038C#150318T064400Zsbecker
003APL Dyalog Extended200918T100226ZRazetime
00305AB1E161009T171748Zacrolith
002Jelly151206T015612Zlirtosia
002Japt x180314T123222ZShaggy
004K ngn/k190422T072805Zmkst
018Perl 6190422T044040Zbb94
006cQuents190305T151738ZStephen
002MathGolf190305T145505Zmaxb
018><>190304T131923ZEmigna
030Kotlin190304T112217Zsnail_
002Brachylog190302T093423ZUnrelate
008Add++180316T161840Zcaird co
025dc180314T155734Zbrhfl
001Pyt180314T142552Zmudkip20
004Stax180314T073640ZWeijun Z
005Pip180314T073226ZDLosc
00916/32bit x86 assembly180314T054034Zpeter fe
008RProgN161010T001859ZATaco
030x86 cpu instructions161009T214256Zuser5898
017ActionScript 3150401T183504ZIlya Gaz
021ES6 34 22150317T093701ZIsmael M
411𝔼𝕊𝕄𝕚𝕟151204T014834ZMama Fun
035Javascript ES6160129T002150ZSuperJed
3127beeswax160122T163504ZM L
045C#151206T171531ZYytsi
018Mathematica150317T091906ZMartin E
003Japt151204T020303ZMama Fun
015Candy151204T064144ZDale Joh
006Seriously151204T053230Zuser4594
009TeaScript151204T015551ZMama Fun
009K5150317T013824ZJohnE
027Clip150317T174629Zbcsb1001
007O150721T043122Zjado
019Julia150317T030647ZAlex A.
021C150317T021651ZLevel Ri
013Matlab150401T194003Zflawr
017Perl 6150401T180415ZBrad Gil
047Bash150322T120603Zpawel.bo
00480386 Machine Code150317T011010Zes1024
049Forth150317T100654ZNagora
042Haskell150320T115251ZHEGX64
018Ruby150320T052710ZGreyCat
045C#150317T132853Zalbertja
042Clojure150318T121817ZNeil Mas
024R150317T151852ZAlex A.
038PHP150317T101008ZIsmael M
051PowerShell150318T141854ZMathias
021Perl150318T134756Znutki
055LUA150318T061543Zjawo
nan><> Fish150317T094546ZSp3000
035perl150317T174357Zmichael5
008WDC 65816150317T171008ZDamian Y
017Python 2150317T032247ZLogic Kn
005J150317T164114ZFUZxxl
021GML Game Maker Language150317T105426ZTimtech
024Go150317T071241ZKristoff
004Joe150317T051931Zseequ
006CJam150317T050515ZOptimize
018Octave150317T041728Zalephalp
006Clip150317T035641ZYpnypn
017Java150317T005425ZTheNumbe
004Pyth150317T003906Zisaacg

C# 8, 41 bytes

C# 8.0 add a new overload to ToString function for convert to binary:

1337.ToString("b").Split('1').Length - 1

https://dotnetfiddle.net/Y2H4eT

Thanks so much to @jdt for a best answer in C# 8:

using System;
                
public class Program
{
    public static void Main()
    {
        int n = 1337;
        Console.WriteLine(int.PopCount(n));
    }
}

https://dotnetfiddle.net/GS8qBO

8051 opcode, 10 bytes

    clr a       ; E4
p:  xch a, r1   ; C9    Grab bit from r1
    rlc a       ; 33    and swap with r0
    xch a, r0   ; C8    so bits come from
    xch a, r1   ; C9    r1 and r0 alternately
    addc a, #16 ; 34 10
    jnc p       ; 50 F8 Sixteen additions
    ret         ; 22    to reach carry

Input r0 and r1, output acc

8086 opcode, 9 bytes

0100 31C0          XOR     AX,AX
0102 D1EF          SHR     DI,1
0104 1410          ADC     AL,10
0106 73FA          JNB     0102
0108 C3            RET

Same idea

Zsh, 25 bytes

<<<${(c)#$(([##2]$1))//0}

Try it online!  27b  30b  35b

Thunno 2 S, 2 bytes

2B

Attempt This Online!

Convert to a binary list. S flag takes the sum.

Thunno 2, 3 bytes

ḃ1c

Attempt This Online!

Convert to binary and count the 1s.

BitCycle, 5 bytes

?+
 !

Online Interpreter

Kind of cheaty, as it inputs in binary and outputs in unary. These are the only two I/O formats this language really can handle, but it's also pretty trivial.


Explanation:

? Take input

+ Send all 0 bits up (deleting them) and all 1 bits down.

! Output all bits that arrive here.

SMALL, 28 bytes

0->n{x?[x%2=1?n+1->n]x/2->x}

Takes input in variable x and the output will be in variable n.

{
  x?
  
  [
    x % 2 = 1?
    n + 1 -> n
  ]
  
  x / 2 -> x
}

Repeatedly divides x by two until the number is zero, which means every 1 bit will be moved into its rightmost bit at some point. We then perform a check each loop to see if this bit is a 1 and if so, increment n.

K (ngn/k), 10 7 bytes

{+/2\x}

Try it online!

Thanks @coltim for -3 bytes by suggesting me that I can just take the sum instead of the count of 1s

Cast the integer into base 2, then sum.

8051 Machine Code, 13 bytes

7B 10 E8 13 50 01 0A BB 08 01 E9 DB F6

Takes the integer in R1 (highest 8 bits) and R0 (lowest 8 bits). Returns the result in R2

    MOV R3, #10        ; 7B 10     - Store 16 since we process a 16 bit number
    MOV A, R0          ; E8        - Move the first register to check to A

LAB1:
    RRC A              ; 13        - Rotate A through the carry to extract the nth bit
    JNC LAB2           ; 50 01     - If the current bit is set (Carry = 1)
    INC R2             ; 0A        - Increment the result

LAB2:
    CJNE R3, #08, LAB3 ; BB 08 01  - If we are done with the first 8 bits
    MOV A, R1          ; E9        - Move R1 into the accumulator

LAB3:
    DJNZ R3, LAB1      ; DB F6     - Jump back to LOOP if we have done less than 16 iterations
END

    

Desmos, 40 38 bytes

f(x)=floor(mod(x/2^{[0...x]},2)).total

Try it on Desmos!

-2 bytes thanks to emanresu A

JavaScript, 19 bytes

f=n=>n&&n%2+f(n>>1)

Try it online!

Nice and simple

PARI/GP, 13 bytes

hammingweight

Attempt This Online!

PARI/GP has a built-in for this.


PARI/GP, 17 bytes

n->sumdigits(n,2)

Attempt This Online!

Another built-in, with a more obvious name.


PARI/GP, 21 bytes

f(n)=if(n,n%2+f(n\2))

Attempt This Online!

Without built-in.

Python 3.10+, 13 bytes

int.bit_count

Attempt This Online!

Factor, 9 bytes

bit-count

Try it online!

Vyxal, 2 bytes

b∑

Try it Online!

Vyxal s, 1 byte

b

Try it Online!

Python, 72 26 bytes

Thanks to mathcat for -12 -27 -36 bytes through various simplifications!

lambda a:bin(a).count('1')

Well, you said statements...

Rust, 15 bytes

u16::count_ones

Try it online!

Rust is better than C because count_ones is shorter than __builtin__popcount :)

Every built-in integer type (unsigned or signed, 8/16/32/64/128 bits) supports this method. Since the challenge specifically asks for unsigned 16 bit integers, we use u16 here. Also, while the method is usually called in the form of some_number.count_ones(), u16::count_ones(some_number) is also a valid syntax for calling the same function.

C# 38 bytes

Convert.ToString(X,2).Count(C=>C==49);

APL (Dyalog Extended), 8 3 bytes

+/⊤

Try it online!

-5 from Adám.

  ⊤ convert to base 2
+/  sum

05AB1E, 3 bytes

bSO

Try it online!

Jelly, 2 bytes

BS

Jelly is a new language written by @Dennis, with J-like syntax.

         implicit: function of command-line arguments
B        Binary digits as list
 S       Sum

Try it here.

Japt -x, 3 2 bytes

ì2

Try it here

K (ngn/k), 4 bytes

+/2\

Try it online!

Convert to base 2, sum up.

Perl 6, 18 bytes

*.base(2).comb.sum

Works with any nonnegative integer, in fact.

Try it online!

cQuents, 6 bytes

uJ$);1

Try it online!

Explanation

:uJ$);1
:            implicit :
              mode: sequence 1 - given input n, output nth term in sequence
             each term in the sequence is

 u   ;1      count(                , 1)
  J )              toBase(     , 2)
   $                      index

MathGolf, 2 bytes

âΣ

Try it online!

Explanation

â    convert to binary
 Σ   sum(list), digit sum(int)

><>, 18 bytes

0$:2%:{+}-2,:@?!n!

Try it online!

Kotlin, 30 bytes

{it.toString(2).sumBy{it-'0'}}

Try it online!

Brachylog, 2 bytes

ḃ+

Try it online!

Just about exactly the Jelly answer.

Add++, 8 bytes

L,BBBDBs

Try it online!

Surprisingly short for Add++

How it works

L,      ; Define a lambda function
        ; Example argument: 1337
    BB  ; Binary;  STACK = [10100111001]
    BD  ; Digits;  STACK = [[1 0 1 0 0 1 1 1 0 0 1]]
    Bs  ; Sum;     STACK = [6]

dc, 25 bytes

[2~rd0<B]dsBx[+z1<S]dsSxp

Try it online!

Two macros. [2~rd0<B]dsBx breaks a decimal value down into binary components by repeatedly dividing by two (using ~ to leave both quotient and remainder on stack) until left with a quotient of zero. After our stack is filled with ones and zeros, [+z1<S]dsSx sums it up by adding the top two values until there's only one value left. p prints our final answer.

Pyt, 1 byte

Hooray for built-ins.

Ħ

Try it online!

Non-built-in:

Pyt, 3 bytes

ɓƖŚ

Try it online!

Explanation:

      Implicit input
ɓ     Convert to binary string
Ɩ     Cast as integer
Ś     Sum of digits
      Implicit output

Stax, 4 bytes

:B|+

Run and debug online!

Explanation

:B|+
:B      Binary digits
  |+    Sum

Pip, 5 bytes

(The language postdates the question, barely.)

1NTBa

Try it online!

With the knowledge that a represents the first command-line argument, this program can be understood quite straightforwardly: 1 iN To-Binary(a). That is, convert a to binary and count the number of 1s.

16/32-bit x86 assembly, 9 bytes

(based on es1024's answer)

31 C0 D1 E9 10 E0 41 E2 F9

which is equivalent to:

xor ax, ax        ; 31 C0   Set ax to 0
shr cx, 1         ; D1 E9   Shift cx to the right by 1 (cx >> 1)
adc al, ah        ; 10 E0   al += (ah = 0) + (cf = rightmost bit before shifting)
inc cx            ; 41      Increment cx to offset following decrement
loop $-5          ; 75 F9   Jump up to shr cx, 1 if cx-1 is not zero

cx is the 16-bit integer to profile, result is returned in ax.

RProgN, 8 Bytes

2 B S ++

Explination

2 B     # Convert to base 2
S       # Convert from string to a stack of individual characters
++      # Sum the stack.

Simple enough, Could be made cheaper if the sugar for sum was single character, instead of double, as ►2BS<SUM> could then be used, saving a byte.

Test Cases

1337:       6.0
16:         1.0
255:        8.0
1236172031: 21.0

x86 cpu instructions, 30 bytes

56 89 E6 8B 44 04 3D 00 00 74 0F D1 E8 50 E8 EF FF 8B 4C 04 81 E1 01 00 01 C8 5E C2 02 00

meaning and disassembly:

; input in the stack sp+4
; output in ax
;0i,2Ka,4P
f:  
push  si
mov   si,  sp
mov   ax,  [si+4]
cmp   ax,  0
je   .z
shr   ax,  1
push  ax
call  f
mov   cx,  [si+4]
and   cx,  1
add   ax,  cx
.z:  
pop   si
ret 2


0000000F  56                push si
00000010  89E6              mov si,sp
00000012  8B4404            mov ax,[si+0x4]
00000015  3D0000            cmp ax,0x0
00000018  740F              jz 0x29
0000001A  D1E8              shr ax,1
0000001C  50                push ax
0000001D  E8EFFF            call 0xf
00000020  8B4C04            mov cx,[si+0x4]
00000023  81E10100          and cx,0x1
00000027  01C8              add ax,cx
00000029  5E                pop si
0000002A  C20200            ret 0x2
//30

ActionScript 3, 17 bytes

for(;x;n++)x&=x-1

This is a copy of steveverrill answer, how ever by using AS3, I don't have to put ; at the end of the line, so I save 1 byte.

Also I assume that x and n been initialize already.

ES6 (34 22 21 bytes):

This is a simple recursive function that can be shortened a bit more. It simply takes a bit and runs itself again:

B=n=>n&&(1&n)+B(n>>1)

Try it on http://www.es6fiddle.net/imt5ilve/ (you need the var because of 'use strict';).

I can't believe I've beaten Fish!!!

The old one:

n=>n.toString(2).split(1).length-1

ES5 (39 bytes):

Both functions can be easily adapted to ES5:

function B(n){return n?(1&n)+B(n>>1):0}

//ungolfed:

function B(number)
{
    if( number > 0 )
    {
        //arguments.callee points to the function itself
        return (number & 1) + arguments.callee( number >> 1 );
    }
    else
    {
        return 0;
    }
}

Old one:

function(n){return n.toString(2).split(1).length-1}

@user1455003 gave me a really great idea, that 'triggered' the smallest one:

function B(n,x){for(x=0;n;n>>=1)x+=n&1;return x}

I've adapted it to ES6 and made it recursive to shorten a lot!

𝔼𝕊𝕄𝕚𝕟, 4 chars / 11 bytes (non-competitive)

⨭⟦ïⓑ

Try it here (Firefox only).

Explanation

Converts input to binary, splits along chars, and gets sum of resulting array.

Javascript ES6, 35 bytes

a=>a.toString(2).match(/1/g).length

beeswax, 31 27 bytes

Non-competing answer. Beeswax is newer than this challenge.

This solution uses Brian Kherigan’s way of counting set bits from the “Bit Twiddling Hacks” website.

it just runs through a loop, incrementing the bit count, while iterating through number=number&(number-1) until number = 0. The solution only goes through the loop as often as there are bits set.

I could shave off 4 bytes by rearranging a few instructions. Both source code and explanation got updated:

pT_
>"p~0+M~p
d~0~@P@&<
{@<

Explanation:

pT_            generate IP, input Integer, redirect
>"             if top lstack value > 0 jump next instruction,
               otherwise continue at next instruction
  p            redirect if top lstack value=0 (see below)
   ~           flip top and 2nd lstack values
    0+         set top lstack value to 0, set top=top+2nd
      M        decrement top lstack value
       ~       flip top and 2nd lstack values
        p      redirect to lower left
        <      redirect to left
       &       top=top&2nd
      @        flip top and 3rd lstack values
    @P         increment top lstack value, flip top and 3rd values
 ~0~           flip top and 2nd values, set top=0, flip top and 2nd again
d              redirect to upper left
>"p~0+M.....   loop back

  p            if top lstack = 0 at " instruction (see above), redirect
  0            set lstack top to zero (irrelevant instruction)
  <            redirect to the left
 @             flip top and 3rd lstack values
{              output top lstack value as integer (bitcount)

Clone my GitHub repository containing the beeswax interpreter, language spec and examples.

C# 45

int o=Convert.ToString(n,2).Count(x=>x=='1');

where o holds the amount of ones and where n is the number.

Alternative and faster C# 6.0 88 bytes

int o=b(n,16).Count(x=>x=='1');
static string b(int v,int l)=>(l>1?b(v>>1,l-1):null)+"01"[v&1];

where the o holds the number of ones and where the n is the number.

Mathematica, 22 18 bytes

Thanks to alephalpha for reminding me of DigitCount.

DigitCount[#,2,1]&

Japt, 3 bytes (non-competitive)

¢¬x

Try it here.

Candy, 15 bytes

I would have thought this would do a bit better, but the lack of an operator to convert numbers to a base 2 string seems to have hurt it. Maybe in a future version of Candy to pull an int from the stack and push 1's and 0's. That would make this one kind of boring, just XS?.

(~A2%h2/LD{)|=Z

The long form is:

while   # stack not empty
  peekA
  pushA    
  digit2
  mod       # get low bit
  popAddZ   # Z = Z + low bit
  digit2
  div
  floor     # integer div 2
  dupl
  if        # if the top of stack is non-zero
endwhile    # NOTE that the endwhile is in an if-then clause
  else
    popA
    pushZ   # NOTE the lack of an endif.
            #  braces and parens are calculated as the
            #  program counter advances over them

Seriously, 6 bytes (non-competitive)

This one is fun and neat, and given the number of non-competitive entries it has attracted, I might as well add a Seriously answer.

'12,¡c

Try it online

Explanation:

'12,¡c
   ,     get input
  2 ¡    convert to binary string
'1   c   count the occurrences of "1"
         (implicit print at EOF)

TeaScript, 9 bytes (non-competitive)

x÷f»l¦1)n

Try it here.

K5, 9 bytes

+/(16#2)\

I used k5's "unpack" overload for \ to split the number into base 2 digits. You can try it online here using oK.

Clip, 22 chars (25 for full program, or 27 for working with zero)

[Fy?!%lyWOO])Fmy#WilyW

Prefix this with F<some value> to get the answer for that value. Or, for a full program to read from stdin, prefix the code with Fnx. In a previous answer, I golfed a way in Clip to check if something's a power of two. I always return one in that case. Otherwise, increment the result of applying this function (recursively) to 2^(floor(log2(<function parameter>))).

To make this work with zero (returning 0), use (28 chars):

[Fy?!yZ]?!%lyWOO])Fmy#WilyW

O, 7 bytes

H2b~]+o

Explanation:

H        Push input into array
  2b~    Push all the bits of the binary form to the array
     ]+o Add them all up and output the array

Julia, 29 27 19 bytes

n->sum(digits(n,2))

This creates an anonymous function that accepts a single argument, n. To use it, assign it to something like f=n->... and call it like f(1337).

The digits() function, when called with 2 arguments, returns an array of the digits of the input in the given base. So digits(n, 2) returns the binary digits of n. Take the sum of the array and you have the number of ones in the binary representation of n.

C,21

for(n=0;x;n++)x&=x-1;

you said "write some statements" (not "a function") so I've assumed the number is supplied in x and the number of 1's is returned in n. If I don't have to initialize n I can save 3 bytes.

This is an adaptation of the famous expression x&x-1 for testing if something is a power of 2 (false if it is, true if it isn't.)

Here it is in action on the number 1337 from the question. Note that subtracting 1 flips the least significant 1 bit and all zeroes to the right.

0000010100111001 & 0000010100111000 = 0000010100111000
0000010100111000 & 0000010100110111 = 0000010100110000
0000010100110000 & 0000010100101111 = 0000010100100000
0000010100100000 & 0000010100011111 = 0000010100000000
0000010100000000 & 0000010011111111 = 0000010000000000
0000010000000000 & 0000001111111111 = 0000000000000000

EDIT: for completeness, here's the naive algorithm, which is one byte longer (and quite a bit slower.)

for(n=0;x;x/=2)n+=x&1;

Matlab, 13 bytes

de2bi creates a vector of zeros and ones representing the binary number, and sum just returns the sum of all the entries.

sum(de2bi(n))

Perl 6: 17

The first thing that comes to mind is

[+] 1337.base(2).comb; # returns 6

Although this doesn't have any arbitrary limits ( the only limits are how much memory you have, and how long you are willing to wait )

[+] ( uint64.Range.max * 2 + 1 ).base(2).comb; # returns 65

# 340282366920938463463374607431768211455
my $uint128-max = :2( 1 x 128 );
[+] $uint128-max.base(2).comb; # returns 128

my $uint8192-max = :2( 1 x 8192 ); # 2467 digit Int
[+] $uint8192-max.base(2).comb; # returns 8192 (takes about a second currently)

Without making it into a Callable the shortest way to write this is to put the Int into the "default" variable $_. ( .method is always short for $_.method )

$_ = 1337;
[+] .base(2).comb;
given 1337 { # Perl6's with/switch statement
  [+] .base(2).comb
}
[+] .base(2).comb given 1337; # ditto
if 1337 -> $_ { # pointy block
  [+] .base(2).comb
}

If you want to create a Callable you could just put it into a Block.

my $code-ref = {[+] .base(2).comb};
# if it is called with an argument it places it in $_
# if called without an argument uses the $_ from an outer scope

If you really want to call it as a normal subroutine:

my &f={[+] .base(2).comb}; # sub f($_){[+] .base(2).comb}

say f 1337; # 6

$_ = 1337;
say f; # 6

Based on your requirements I'd guess that the answer you are looking for is:

[+] .base(2).comb

This assumes that the value is already in $_. It would most likely be the last statement in a subroutine, the right side of an assignment, or an argument to a subroutine or method. ( Otherwise it calculates the result only to throw it away, unless the compiler notices that the result is unused )


In case you were wondering [+] 1, 2, 3 can be considered short for (1,2,3).reduce(&[+]).
Where &[+] is short for &infix:< + > the collection of multi subs available in the current scope that are responsible for the numerical infix addition operator +.

Bash, 63 51 47 bytes

[ $1 = 0 ]&&echo 0||echo $[$1%2+`$0 $[$1/2]`]

The shorter the code, the clearer the meaning :).


51:

[ $1 -ne 0 ]&&echo $[($1&1)+$($0 $[$1/2])]||echo 0

Recursive script instead of script with recursing function.


The "negative-cond || instruction" idiom instead of boring "if cond; then instruction; fi " is our friend here.

Note that echo should return 0 (true), so [ $1 -ne 0 ] && echo $[$[$1&1]+$(n $[$1/2])]

has the logical value of [ $1 -ne 0 ] alone.

80386 Machine Code, 4 bytes

F3 0F B8 C1

which takes the integer in cx and outputs the count in ax, and is equivalent to:

popcnt ax, cx     ; F3 0F B8 C1

And here is an 11 10 byte solution not using POPCNT:

31 C0 D1 E9 10 E0 85 C9 75 F8

which is equivalent to:

xor ax, ax        ; 31 C0   Set ax to 0
shr cx, 1         ; D1 E9   Shift cx to the right by 1 (cx >> 1)
adc al, ah        ; 10 E0   al += (ah = 0) + (cf = rightmost bit before shifting)
test cx, cx       ; 85 C9   Check if cx == 0
jnz $-6           ; 75 F8   Jump up to shr cx, 1 if not

Forth, 48 49 bytes

: c ?dup if dup 1- and recurse 1+ then ;
0 1337 c

If an actual function is needed then the second line becomes

: c 0 swap c ;

and you call it by "1337 c". Forth's relatively verbose control words make this a tough one (actually, they make a lot of these tough).

Edit: My previous version did not handle negative numbers correctly.

Haskell 42 chars

t 0=[]
t n=t(quot n 2)++[rem n 2]
f=sum.t

declares the function f :: Integer -> Integer
use from the interactive interpreter as f <number> or add the line main=print$f <number> to the end of the file.

Ruby, 18 bytes

n.to_s(2).count'1'

C#, 45 bytes

Convert.ToString((ushort)15,2).Sum(b=>b-48);

https://dotnetfiddle.net/kJDgOY

Clojure, 42 bytes

#(count(filter #{\1}(Long/toString % 2)))

Reading right to left, convert to a binary string, convert to a sequence of characters, filter on 1s and count how many you have.

EDITED With help from Sieg

R, 24 bytes

sum(intToBits(scan())>0)

scan() reads input from stdin.

intToBits() takes an integer and returns a vector of type raw containing the zeroes and ones of the binary representation of the input.

intToBits(scan())>0 returns a logical vector where each element is TRUE if the corresponding binary vector element is a 1 (since all elements are 0 or 1 and 1 > 0), otherwise FALSE.

In R, you can sum a logical vector to get the number of TRUE elements, so summing the vector of logicals as above gets us what we want.

Note that sum() can't handle raw input directly, hence the workaround using logicals.

PHP (38 bytes):

This uses the same aproach as my ES6 answer

<?=count(split(1,decbin($_GET[n])))-1;

This is a full code, you only need to put it in a file and access it over the browser, with the parameter n=<number>.

PHP <4.2 (32 bytes):

This is a little shorter:

<?=count(split(1,decbin($n)))-1;

This only works reliably on PHP<4.2 because the directive register_globals was set to Off by default from PHP4.2 up to PHP5.4 (which was removed by then).

If you create a php.ini file with register_globals=On, this will work.

To use the code, access the file using a browser, with either POST or GET.

@ViniciusMonteiro's suggestion (38/45 bytes):

He gave 2 really good suggestions that have a very interesting use of the function array_sum:

38 bytes:

<?=array_sum(str_split(decbin(1337)));

45 bytes:

<?=array_sum(preg_split('//', decbin(1337)));

This is a really great idea and can be shortened a bit more, to be 36 bytes long:

<?=array_sum(split(1,decbin(1337)));

PowerShell (51 bytes)

"$([char[]][convert]::ToString($s,2)|%{"+$_"})"|iex

Explanation:
[convert]::ToString($s,2) produces a binary string representation from $s.
[char[]] casts it as a char array and allows us to enumerate each char.
|%{"+$_"} prepends each character with a + sign
"$()" implicitly calls .ToString() on the resulting sub expression
|iex sums the piped string (ie. "+1 +0 +1 +1 +0 +1 +0 +0" = 4)

Perl, 21

$r=grep$v&1<<$_,0..15

LUA 55 bytes

while(i>0)do if(v-i)>=0 then c=c+1;v=v-i;end i=i/2 end

v is the value

i is the max value of an (x)bit Integer, 65535 in this example.

c counts one up, if there's a remainder from (i-l), which means that a one is found.

This is more a simple algorithm than a single statement.

><> (Fish), 24 bytes + 2 = 26

0$11.>~n;
2,:?!^:2%:{+}-

The program just does repeated mod 2, subtract and divide until the input number becomes zero, then prints the sum of the mod 2s.

Test with the -v flag, e.g.

py -3 fish.py ones.fish -v 1337

perl (35 characters)

$b=sprintf("%b",$d);$c=()=$b=~/1/g;

WDC 65816, 8 bytes

Assuming 8-bit XY (P.x = 1), the following 8 bytes of object code produce the popcnt of A in X within 145 cycles:

A2 00 4A 90 01 E8 D0 FA

This works on a 65816 whether A is 8-bit (P.m = 1) or 16-bit (P.m = 0), and it has also been tested in a virtual 6502 with 8-bit values. With 16-bit XY on a 65816 (P.x = 0), one more byte is needed: replace A2 00 with A2 00 00.

Assembly source:

  ldx #0       ; A2 00, or A2 00 00 in 16-bit XY mode
loop:
  lsr a        ; 4A    Copy bit 0 of A to carry and shift A right by 1
  bcc zerobit  ; 90 01 If carry is 1, add 1 to X
  inx          ; E8
zerobit:
  bne loop     ; D0 FA If the last ALU result was nonzero, keep counting

The bne instruction branches on the zero flag, which changes whenever an instruction writes to register A, X, or Y. For a 1 bit, inx is the last instruction to write to A, X, or Y, and X is nonzero if there are 1 to 255 bits (only 16 are possible!), so the loop continues. For a 0 bit, lsr a is the last instruction to write to A, X, or Y, and A is nonzero only if there are more bits to count.

Python 2, 17 bytes

bin(s).count('1')

The bin built-in returns the integer converted to a binary string. We then count the 1 digits:

>>> s=1337
>>> bin(s)
'0b10100111001'
>>> bin(s).count('1')
6

J (5 characters)

J has no explicit types. This does the right thing for all integers.

+/@#:

GML (Game Maker Language), 21 bytes

for(n=0;x;n/=2)n+=x&1

Go, 24

This is an adaptation of the C solution by @steveverrill

n:=0;for;x>0;n++{x&=x-1}

We need to explicitly declare n outside the loop to keep it in scope.

Go requires curly braces as well, and the check in the for loop must be a boolean expression.

http://play.golang.org/p/Z_iuGL5nZ5

Joe, 4 bytes

/+Ba

This is an anonymous function. Ba gives the binary representation of a number and /+ sums it.

   (/+Ba)13
3
   (/+Ba)500
6

CJam, 6 bytes

ri2b:+

ri         "Read the input and convert it to integer";
  2b       "Convert the integer into base 2 format";
    :+     "Sum the digits of base 2 form";

Try it online here

Octave, 18

sum(dec2bin(s)-48)

Example:

octave:1> s=1337
s =  1337
octave:2> sum(dec2bin(s)-48)
ans =  6

Clip, 6

2 ways:

cb2nx1

This is a straightforward translation of the requirement: the count of ones in the base-2 representation of number.

r+`b2n

Another method, which takes the sum of the digits of the base-2 representation.

Java, 17 bytes

Works for byte, short, char, and int. Use as a lambda.

Integer::bitCount

Test here

Without using built-ins:

42 bytes

s->{int c=0;for(;s!=0;c++)s&=s-1;return c}

Test here

Pyth, 4 bytes

sjQ2

The program takes the number whose hamming weight is to be found on STDIN.