g | x | w | all
Bytes Lang Time Link
068Tcl250604T210453Zsergiol
066Google Sheets / Excel250607T004420Zz..
037AWK250606T233633Zxrs
028Swift 6250502T180632ZmacOSist
008Thunno 2 L230509T175948ZThe Thon
6125Vyxal l230509T175146Zemirps
065awk221101T133707ZRARE Kpo
010386 opcode171228T144500Zl4m2
012MathGolf190320T143404Zmaxb
037Forth gforth190319T150804Zreffu
014dc190319T144835ZSophia L
020><>190319T142656ZEmigna
034brainfuck171229T031833ZJo King
032J171229T014016ZBolce Bu
nanJavaScript171228T150403Zl4m2
066SNOBOL4 CSNOBOL4171228T143115ZGiuseppe
026Mathematica120926T220646ZDavidC
012Pushy171227T183315ZFlipTack
025Python 2170720T192556ZKoishore
036PHP170720T193106Zhalfmang
066C120101T101911ZPaul R
030TIBasic TI84 Plus CE170331T163955Zpizzapan
036Java 7161216T184652ZPoke
042JavaScript111230T153415Zmellamok
100sed160125T163516ZToby Spe
050JavaScript150708T031329ZJamie
002Brainbool150708T021302Zlirtosia
021GolfScript130503T080921Zaditsu q
026dc –121031T230656Zdaniero
035excel121031T132733ZSeanC
045Ocaml120926T202725ZReyCharl
019Op120225T003247ZRy-
045C120123T174923ZMr. Llam
057PHP120129T212618ZArjan
nanIsn't reading a number into binary or printing the number from binary a "builtin base conversion function"120121T145934ZJeff Bur
nan120120T014928ZSamuel D
052 OCaml120103T004719ZLeah Xue
053C111231T013738Zsam hoce
060Haskell120101T152833Zmarinus
053Brainfuck120101T152657Zcopy
071JavaScript111230T223203Zpimvdb
012Common Lisp111231T041913ZJoanis
012APL111230T210652ZDillon C
013J111230T182509ZGareth
036Perl111230T154630ZPhiNotPi
030Perl111230T203918ZIlmari K
016GolfScript111230T162124ZHoward
053R111230T185324ZBrian Di
065Python 48 without spaces111230T171153Zelssar
038Ruby111230T165920ZHoward
041Python 2.6111230T164840ZSteven R
045Python 2.6111230T161538ZSteven R
070D111230T161407Zratchet
086Scala111230T154358ZGareth

Tcl, 68 bytes

proc C n {while \$n {incr b [expr $n%2]
set n [expr $n/2]}
incr b 0}

Try it online!


# [Tcl], 72 bytes
proc C {n b\ 0} {while \$n {incr b [expr $n%2]
set n [expr $n/2]}
set b}

Try it online!

Google Sheets / Excel, 66 bytes

=LET(F,LAMBDA(F,q,r,IF(q/2,F(F,INT(q/2),r+MOD(q,2)),r)),F(F,A1,0))

AWK, 37 bytes

{for(x=0;$1=int($1/2);)x+=$1%2}1,$0=x

Attempt This Online!

{for(            # loop
x=0;             # if input is zero
$1=int($1/2);)   # binary breakdown
x+=$1%2}         # add digit to total
1,$0=x           # set output

Swift 6, 28 bytes

let f={$0<1 ?0:$0%2+f($0/2)}

Try it on SwiftFiddle!

This solution was 2 bytes shorter than using the builtin:

let f={($0+0).nonzeroBitCount}

Why Swift has a builtin for this, I'll never know.

Thunno 2 L, 8 bytes

LOʠæS=;Ḟ

Port of emirps's Vyxal answer.

Explanation

LOʠæS=;Ḟ  # Implicit input
LO        # Push 2 ** [0..input)
  ʠ       # Powerset of this list
   æ  ;   # Filtered by:
    S=    #  Sum equals the input
       Ḟ  # Flatten this list of lists
          # L flag gets the length
          # Implicit output

Screenshot

Screenshot

Vyxal l, 49 bits1, 6.125 bytes

ʀEṗ'∑?=;f

Try it Online!

Brute force solution, so the online interpreter times out. May potentially be made shorter by porting others, but I thought this solution was fun

ʀ         # range 0..input+1
 E        # raise 2^n for each value in that range
  ṗ       # powerset
   '   ;  # filtered by
    ∑     # the sum
     ?=   # is equal to the input?
        f # flatten
          # after which the l flag takes the length of the top of the stack and implicitly outputs it

awk, 65 bytes

__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""

Example:

echo "56432\n45781254\n0" | 

mawk '__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""'

8
11
0

386 opcode, 10 Bytes

2BC0                       SUB EAX,EAX
01C9                       ADD ECX,ECX
1400                       ADC AL,0
41                         INC ECX
E2F9                       LOOP $-5
C3                         RET

Thank Peter Cordes for 1B save and 1B rule save

MathGolf, 12 bytes

æ_╫`¡▲ÞĽ↑;î

Try it online!

This fails for input 0, due to a bug in MathGolf. I'll explain why. But I thought it was a fun solution to this problem that might not be obvious.

This method could be seen as disallowed, but I refer to wikipedia: "The bit shifts are sometimes considered bitwise operations, because they treat a value as a series of bits rather than as a numerical quantity" (emphasis mine). I have chosen to interpret this to mean that MathGolf's bitshifts are allowed, since they don't operate on a fixed number of bytes. Bit rotating in MathGolf wraps the current number of bits in the number, and rotates using the bit width of the number. Thus, if you do this enough times, any number with \$n\$ set bits will converge to \$2^n-1\$. If you then divide the result by 2 until you reach 0, the number of divisions will represent the number of ones in the original number.

The reason that this fails for 0 is that 0 is somehow turned into 1 when left-rotated. This is a bug in the implementation of the operator, rather than this program itself, and should be fixed in an upcoming update.

Explanation

æ    ▲         do-while true using 4 operators
 _             duplicate TOS
  ╫            left-rotate bits in int, list/str
   `           duplicate the top two items
    ¡          push a, b, push a != b
               This do-while loop repeats until the left-rotated
      Þ        not implemented yet
       Ä       start block of length 1
        ½      pop a : push(a//2 if int else a/2)
         ↑     while true without popping
          ;    discard TOS
           î   index of current loop (1-based)

Forth (gforth), 37 bytes

: f dup 0> if 2 /mod recurse + then ;

Try it online!

Usually recursion isn't worth it when golfing Forth because it requires the if, then, (possible else), and recurse words. In this case we can do without else and we save more in stack-manipulation than we lose from recursion

Explanation

Code Explanation

: f         \ start new word definition
  dup       \ duplicate top stack value
  0> if     \ if top stack value is greater than 0
    2 /mod  \ get quotient and remainder of dividing by 2 (quotient on top of stack)
    recurse \ execute current word
    +       \ add remainder to result of recursion
  then      \ end if statement
;           \ end word definition

dc, 14 bytes

[2~rd0<M+]dsMx

Try it online!

Input is taken from the stack, output is left on the stack. This is the same general idea as the previous dc entry (repeatedly reduce mod 2 and add remainders), but optimizing by using non-tail recursion makes a huge difference (I'd have made this a comment on that entry, but the user hasn't been active for over a year).

><>, 20 bytes

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

Try it online!

brainfuck, 34 bytes

>+<[[>-]++[>]+[<]>-]>[-<[->+<]>>]<

Try it online!

At 53 bytes, I thought the existing brainfuck solution was way too long /s. Starting cell contains the number and ends on the number of binary digits in it. Doesn't work for numbers above 255 unless you use an interpreter with larger than 8 bit or infinite cells.

How It Works

>+<[[>-]++[>]+[<]>-] Converts the number to binary
>[-<[->+<]>>]<       Adds all the numbers in the binary together

J, 32 Bytes

There's probably a more mathematical way to do this that doesn't require finding the binary representation, but I thought this was pretty good none the less:

+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])

Explanation:

+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])  | Full program
    (                          )  | Convert to binary list:
     (                     )^:]   | do n times:
      }:                            | Curtail the list
        ,(|~2:)@{:                  | Append the remainder mod 2 of the item dropped
                  ,<.@-:@{:       | Append the floor of half the item dropped
+/@:                                | Sum

A step by step example:

    (}:,(|~2:)@{:,<.@-:@{:) 7
1 3
^ ^
| | 
| Floor 7/2
7 % 2

    (}:,(|~2:)@{:,<.@-:@{:) 1 3
1 1 1
^ ^ ^
| | |
| | Floor 3/2
| 3 % 2
The input curtailed

    ((}:,(|~2:^#)@{:,<.@-:@{:)^:]) 7
1 1 1 0 0 0 0 0

    +/@:((}:,(|~2:)@{:,<.@-:@{:)^:]) 7
3

Of course, you would only have to do this Ceil(log2 n) times, but thats a lot harder to calculate than just n.

JavaScript, 43 Bytes, assuming 1/2/2/2/...=0

for(a=prompt(b=0);a;a/=2)b+=a%2>=1;alert(b)

SNOBOL4 (CSNOBOL4), 66 bytes

	X =INPUT
I	O =O + REMDR(X,2)
	X =GT(X) X / 2	:S(I)
	OUTPUT =O
END

Try it online!

Mathematica 26

Count[n~IntegerDigits~2,1]

Pushy, 12 bytes

$&2%v2/;O_S#

Try it online!

While the input is bigger than 0, it has its least significant bit (using mod) pushed to the second stack, then it is halved (integer division). Once all bits have been placed on the second stack, it is summed and the result is printed.

Python 2, 25 bytes

lambda n:n and n%2+f(n/2)

Try it online!

PHP, 36 bytes

while($n){$o+=$n%2;$n/=2*1;}echo $o;

Assumes $n is the number to be tested, shows a PHP Notice for $o, and doesn't exactly work when $n is 0 (outputs nothing).

PHP, 53 bytes

$n=$argv[1];$o=0;while($n){$o+=$n%2;$n/=2*1;}echo $o;

Accepts command-line input, doesn't show a PHP Notice, and outputs correctly for 0.

C, 66 characters

main(int n,char **a){printf("%u",__builtin_popcount(atoi(a[1])))};

Note: requires gcc or gcc-compatible compiler (e.g. ICC, clang).

For some CPUs __builtin_popcount compiles to a single instruction (e.g. POPCNT on x86).

TI-Basic (TI-84 Plus CE), 30 bytes

Prompt X
0→S
While X
S+remainder(2,X→S
int(X/2→X
End
S

TI-Basic is a tokenized language, all tokens but remainder( are one-byte, remainder is two

Java 7, 36 bytes

int b(Long a){return a.bitCount(a);}

Because of course this, of all things, is something that Java has a builtin for...

JavaScript, 49 47 45 42 bytes

for(n=prompt(o=0);n=n/2|0;o+=n%2);alert(o)

Demo: http://jsfiddle.net/hcYdx/4/

Edit 1: remove q and use ~~ for rounding, save 2 chars.

Edit 2: use |0 rounding operator instead of ~~ to save parentheses (2 chars).

Edit 3: simplify n>0 to n and combine with n=n/2|0 to make entire condition; now have wasted statement space :(

sed, 100 bytes

:
s/[13579]/&;/g
y/123456789/011223344/
s/;0/5/g
s/;1/6/g
s/;2/7/g
s/;3/8/g
s/;4/9/g
/[1-9]/b
s/0//g

Output is in unary; if you want it in decimal, pipe through wc -c or append the following converter (GNU sed -r):

# unary to decimal
:d
s/;;;;;/v/g
s/vv/x/g
s/x([0-9]|$)/x0\1/
s/;;/b/g
s/bb/4/
s/b;/3/
s/v;/6/
s/vb/7/
s/v3/8/
s/v4/9/
y/;bvx/125;/
td

This implements successive division by 2, accumulating carry-out as output. It is able to handle fairly large inputs; for example I tested the all-ones 8192-bit input thus:

$ dc <<<'2 8192^1-p' | tr -d '\\\n' | ./4434.sed | wc -c
8192

and the mostly-zeros of similar length:

$ dc <<<'2 8192^p' | tr -d '\\\n' | ./4434.sed | wc -c
1

JavaScript, 57 55 51 50 bytes

a=prompt(b=0);while(a){b+=a%2;a=(a-a%2)/2}alert(b)

Modulo is not bitwise operator ☺

Brainbool, 2

,.

The most reasonable interpretation, in my opinion (and what most of the answers use) of "highest number your language is able to handle" is "largest number your language natively supports". Brainbool is a brainfuck derivative that uses bits rather than bytes, and takes input and output in binary (0 and 1 characters) rather than character codes. The largest natively supported number is therefore 1, and the smallest is 0, which have Hamming weights 1 and 0 respectively.

Brainbool was created in 2010, according to Esolang.

GolfScript - 21

~{.2%{0):0;}*2/.}do;0

dc – 26 chars

This is rather long, mostly due to the lack of loop constructs in dc.

0?[d2%rsi+li2/d0<x]dsxx+p

Keeps adding up the modulo 2 of the number and dividing the number by to until it reaches zero. Can handle arbitrarily long integers.

Example:

$ dc -e '0?[d2%rsi+li2/d0<x]dsxx+p' <<< 127
7
$ dc countones.dc <<< 1273434547453452352342346734573465732856238472384263456458235374653784538469120235
138

excel, 35

=LEN(A1)-LEN(SUBSTITUTE(A1,"1",""))

Ocaml, 45 characters

Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else.

let rec o=function 0->0|x->(x mod 2)+(o(x/2))  

Op, 23 19 (discontinued language of my invention)

0N[1~!?@2%{1+}2/])I

Here's a commented version:

0 # push a 0 onto the stack
N # read an integer from STDIN onto the stack
[ # begin an infinite loop
    1 # push a 1 onto the stack
    ~ # pop the 1 off the stack, and duplicate the top 1 items (i.e. the read number)
    ! # pop a number, push 1 if 0 or 0 otherwise (NOT)
    ? # pop a number, if the number is nonzero...
    @ # ... then break out of the infinite loop. Basically, break out when N reaches 0.
    2 # push a 2 onto the stack
    % # pop number "a" off the stack, then number "b", and push b modulo a.
    { # rotate the stack left
    1 # push a 1 onto the stack
    + # pop a and b, and push a + b (increment)
    } # rotate the stack right
    2 # push a 2 onto the stack
    / # pop number "a" off the stack, then number "b", then push b / a (int)
] # repeat back to start of loop
) # shift the stack right, taking off the 0 and leaving only the result
I # output the result as a number to STDOUT

C, 45

f(n,c){for(c=0;n;n/=2)c+=n%2;printf("%d",c);}

Nothing really special here for golfing in C: implicit return type, implicit integer type for parameters.

PHP, 57

$i=$s=0;for(;$i<log($n,2);){$s+=$n/pow(2,$i++)%2;}echo$s;

This assumes that $n holds the value to be tested.

PHP, 55 (alternative solution)

function b($i){return$i|0?($i%2)+b($i/2):0;}echo b($n);

Again, this assumes that $n holds the value to be tested. This is an alternative because it uses the or-operator to floor the input.

Both solutions work and do not cause notices.

Isn't reading a number into binary or printing the number from binary a "builtin base conversion function", thus invalidating every answer above that prints an integer? If you permit reading and printing an integer, like almost all the above answers do, then I'll make claims using a builtin popcount function :

Haskell, 50

There was a popCount routine added to the Data.Bits module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the primop and binding).

import Data.Bits
main=interact$show.popCount.read

I cannot beat the above Python and Perl scores using their GMPY or GMP::Mpz modules for GMP sadly, although GMP does offer a popcount function too.

Scheme

I polished the rules a bit to add to the challenge. The function doesn't care about the base of the number because it uses its own binary scale. I was inspired by the way analog to numeric conversion works. I just use plain recursion for this:

(define (find-ones n)
  (define (nbits n)
    (let nbits ([i 2])
      (if (< i n) (nbits (* i 2)) i)))
  (let f ([half (/ (nbits n) 2)] [i 0] [n n])
    (cond [(< half 2) i]
      [(< n i) (f (/ half 2) i (/ n 2))]
      [else (f (/ half 2) (+ i 1) (/ n 2))])))

OCaml, 52 characters

let rec o x=if x=0 then 0 else (x mod 2) + (o (x/2))

C, 61 60 57 53 characters

void f(x){int i=0;for(;x;x/=2)i+=x%2;printf("%u",i);}

The function body only is 38 characters. Edit: removed bitwise operator Edit: put printf out of the loop as suggested in the comments Edit: switch to K&R declaration; also, this is no longer C99-specific

Haskell (60 chars)

f n=sum[1|x<-[0..n],odd$n`div`2^x]
main=interact$show.f.read

Brainfuck, 53 characters

This was missing an obligatory Brainfuck solution, so I made this one:

[[->+<[->->>>+<<]>[->>>>+<<]<<<]>>>>[-<<<<+>>>>]<<<<]

Takes number from cell 1 and puts the result into cell 6.

Unenrolled and commented version:

[  while n != 0
  [  div 2 loop
    -
    >+<  marker for if/else
    [->->>>+<<]  if n != 0 inc n/2
    >
    [->>>>+<<]  else inc m
    <<<
  ]
  >>>>  move n/2 back to n
  [-<<<<+>>>>]
  <<<<
]

JavaScript, 78 72 71 characters

I'll post my initial solution which I came up with before posting the question as well. There is already a much better JavaScript answer though :)

for(n=prompt(a=0),j=1;j<=n;j*=2)for(i=j;i<=n;i+=2*j)n<i+j&&a++;alert(a)

http://jsfiddle.net/Mk8zd/1/

The idea comes from certain "mind reading cards" which enable you to obtain the number someone else has in mind, by showing them cards and let them say on which cards their number is apparent.

It works because each number is a unique combination of 1s / 0s in binary. My solution checks on which "cards" the number is apparent so as to determine how many 1s it has. It's just not very efficient, though...

I found this document which outlines the mind reading technique.

Common Lisp, 12 chars

(assuming a 1 char variable name - i.e.: 11 + number length)

It's not a base conversion function, so it should work:

(logcount x)

Examples:

[1]> (logcount 0)
0
[2]> (logcount 1)
1
[3]> (logcount 1024)
1
[4]> (logcount 1023)
10
[5]> (logcount 1234567890123456789012345678901234567890)
68

(Using GNU CLISP.)

APL, 9 12 characters

+/2|⌊⎕÷2*⍳32

This assumes that the interpreter uses 32-bit integers, and that ⎕IO is set to 0 (meaning that monadic begins with 0, rather than 1). I used the 32-bit version of Dyalog APL.

Explanation, from right to left:

Not quite 9 characters anymore. :(

Old, rule-breaking version:

+/⎕⊤⍨32/2

Explanation, from right to left:

  • 32/2: Replicate 2, 32 times.
  • commutes the dyadic function to its left, which in this case is (i.e., X⊤⍨Y is equivalent to Y⊤X).
  • is the encode function. It encodes the integer to its right in the base given to its left. Note that, because of the commute operator, the right and left arguments are switched. The base is repeated for the number of digits required, hence 32/2.
  • is a niladic function that accepts user input and evaluates it.
  • +/ reduces (folds) its right argument using +. (We add up the 0's and 1's.)

J, 13 characters

(+ the number of digits in the number)

+/2|<.n%2^i.32

Usage: replace the n in the program with the number to be tested.

Examples:

+/2|<.56432%2^i.32
8
+/2|<.45781254%2^i.32
11
+/2|<.0%2^i.32
0

There's probably a way of rearranging this so the number can be placed at the beginning or end, but this is my first J entry and my head's hurting slightly now.

Explanation(mainly so that I understand it in the future)

i.32 - creates an array of the numbers 1 to 32

2^ - turns the list into the powers of two 1 to 4294967296

n% - divides the input number by each element in the list

<. - rounds all the divison results down to the next integer

2| - same as %2 in most languages - returns 0 if even and 1 if odd

+/ - totals the items in the list (which are now just 1s or 0s)

Perl, 45 43 36 Characters

$n=<>;while($n){$_+=$n%2;$n/=2}print

Thanks to Howard for 45->43, and to User606723 for 43->36.

Perl, 30 chars

$==<>;1while$_+=$=%2,$=/=2;say

Based on PhiNotPi's solution, with some extra golfing. Run with perl -M5.010 to enable the Perl 5.10 say feature.

GolfScript, 17 16 characters

~{.2%\2/.}do]0-,

Edit: new version saves 1 character by using list operation instead of fold (original version was ~{.2%\2/.}do]{+}*, direct count version: ~0\{.2%@+\2/.}do;).

R, 53 characters

o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())

Examples:

> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 56432
2: 
Read 1 item
[1] 8
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 45781254
2: 
Read 1 item
[1] 11
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 0
2: 
Read 1 item
[1] 0

If inputting the number is not part of the character count, then it is 43 characters:

o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0}

with test cases

> o(56432)
[1] 8
> o(45781254)
[1] 11
> o(0)
[1] 0

Python (48 without spaces, 65 with)

x = int(raw_input())
s = 0
while x:
    if x%2:
        s+=1
    x/=2
print s

Ruby, 38 characters

f=->u{u<1?0:u%2+f[u/2]}
p f[gets.to_i]

Another solution using ruby and the same recursive approach as Steven.

Python 2.6, 41 characters

t,n=0,input()
while n:t+=n%2;n/=2
print t

note: My other answer uses lambda and recursion and this one uses a while loop. I think they are different enough to warrant two answers.

Python 2.6, 45 characters

b=lambda n:n and n%2+b(n/2) 
print b(input())

D (70 chars)

int f(string i){int k=to!int(i),r;while(k){if(k%2)r++;k/=2;}return r;}

Scala, 86 characters

object O extends App{def f(i:Int):Int=if(i>0)i%2+f(i/2)else 0
print(f(args(0).toInt))}

Usage: scala O 56432