[Question]
  [
# Challenge :
Count the number of ones `1` in the binary representation of all number between a range.
---
# Input :
Two non-decimal positive integers
---
# Output :
The sum of all the `1`s in the range between the two numbers.
---
# Example :
```
4 , 7        ---> 8
4  = 100 (adds one)   = 1
5  = 101 (adds two)   = 3
6  = 110 (adds two)   = 5
7  = 111 (adds three) = 8
10 , 20     ---> 27
100 , 200   ---> 419
1 , 3       ---> 4
1 , 2       ---> 2
1000, 2000  ---> 5938
```
I have only explained the first example otherwise it would have taken up a huge amount of space if I tried to explain for all of them.
---
# Note :
* Numbers can be apart by over a 1000
* All input will be valid.
* The minimum output will be one.
* You can accept number as an array of two elements.
* You can choose how the numbers are ordered.
---
# Winning criteria :
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each language wins.
  
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
f=lambda x,y:y/x and bin(x).count('1')+f(x+1,y)
```
[Try it online!](https://tio.run/##LYzNCsIwEAbP@hTfpSRLV21aQSjou6SWYEA3paSQPH38iZeZOc2S4yNIX4q7Pu1rmi0S5zGfEqzMmLzoRMd72CRqZRS1TqfWcKbiwgqdGJngBfrMuBBDm47Rd7V@WZsx/N3TuN8tq5cI1Qwb4wMcbl8pNHXJcHVN5Q0 "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 38 bytes
Takes input in currying syntax `(a)(b)`.
```
a=>b=>(g=c=>a>b?0:1+g(c^c&-c||++a))(a)
```
[Try it online!](https://tio.run/##bcxBCsIwEIXhvaeYlWQItUksVAuJNxGmYxuU0kgrrnr3GDGr4OZtPt7/oDetvNyfr2oOtyGONpJ1vXXCW7aOXH9RnZZe8JX3FW@blIQoCCOHeQ3TcJiCF6MAaDBNiwh1DaddoVolNeqnpi1Yq8RGZW70ubyD/saP2f@ryfH4AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
a => b => (         // given the input values a and b
  g = c =>          // g = recursive function taking c = current value
    a > b ?         // if a is greater than b:
      0             //   stop recursion and return 0
    :               // else:
      1 +           //   add 1 to the final result
      g(            //   and do a recursive call to g() with:
        c ^ c & -c  //     the current value with the least significant bit thrown away
        || ++a      //     or the next value in the range if the above result is 0
      )             //   end of recursive call
)(a)                // initial call to g() with c = a
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
rBFS
```
[Try it online!](https://tio.run/##y0rNyan8/7/IyS34////Jv/NAQ "Jelly – Try It Online")
### Explanation
```
rBFS – Full program. Takes the two inputs from the commands line arguments.
r    – Range.
 B   – For each, convert to binary.
  FS – Flatten and sum.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
ŸbSO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6I6kYP///024zAE "05AB1E – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 55 bytes
```
a->b->{int c=0;for(;a<=b;)c+=a.bitCount(b--);return c;}
```
[Try it online!](https://tio.run/##LY5BS8QwEIXv/RVzTNQED4KHbAsiCB7Ew@JJPEyyaUlNk5BMFsrS317j6umbx5uZ92Y8o5hP37tbUswEc9OykvNyrMGQi0HeqM54LAXe0AW4dACpau8MFEJqOEd3gqV57EjZhenzCzBPhV9XAV7@/xxeA9nJ5rvGj4B5fU82I8U8wNjvKAYthosLBKa/V2PMTOGh14qb2x6ldvQcayCmheAqW6o5gFHbrq4Zx7WQXWSsJFOrQD6wUWJKfmUP/G94Ki2XPXL@e7F12/4D "Java (JDK 10) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes
1 byte thanks to Mr. Xcoder.
```
ssjR2}F
```
[Try it online!](http://pyth.herokuapp.com/?code=ssjR2%7DF&input=4%2C7&debug=0)
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
lambda x,y:`map(bin,range(x,y+1))`.count('1')
```
[Try it online!](https://tio.run/##LYxBCsIwFETXeorZlOTjV5pUEAp6EhdN1WihTUJJwZw@VuNm3mMGJqT48k5nizOueTRTfzd4c2q7yQTZD45n454PuVY7RdQdbn5xUQolKFs/Yx2QCIODPDJOxJCqZui62E@LM5o/NbXbTZgHFyGqZmGsgf3lC4GqXDJsuab8AQ "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes
```
&:Bz
```
[Try it online!](https://tio.run/##y00syfn/X83Kqer/fxMucwA "MATL – Try It Online")
*Thanks to Luis Mendo for saving a byte!*
```
(implicit input a and b, a<b)
&:                              % two-element input range, construct [a..b]
  B                             % convert to Binary as a logical vector (matrix)
   z                            % number of nonzero entries
(implicit output of the result)
```
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 34 bytes
```
function(a,b)sum(intToBits(a:b)>0)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJs7g0VyMzryQk3ymzpFgj0SpJ085A83@ahomOuSZXmoahgY6RAYQBYkGYOsYQykjzPwA "R – Try It Online")
Heavily inspired by [the other R solution by ngm](https://codegolf.stackexchange.com/a/166216/80010). This uses a different approach after the conversion to bits. Huge thanks to Giuseppe for hinting at a possible 34 bytes solution.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a,b{("%b"*(b-a+1)%[*a..b]).count ?1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6laQ0k1SUlLI0k3UdtQUzVaK1FPLylWUy85vzSvRMHesPZ/QWlJsUJatImOeex/AA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://github.com/abrudz/SBCS)
```
{≢⍸(⍵⍴2)⊤⍺↓0,⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR56JHvTs0HvVufdS7xUjzUdeSR727HrVNNtB51LsZKFr7//@j3rkK4Zk5OQq5idmpCpklCkmpJSWpRQo5iUBSj4vL0MBAoVr7Uc9@HTzGKBgZGAAA "APL (Dyalog Unicode) – Try It Online")
-1 thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz).
Left argument = min  
Right argument = max
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Communication toolbox, 21 bytes
```
@(a,b)nnz(de2bi(a:b))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnSTMvr0ojJdUoKVMj0SpJU/N/moaJjrkmV5qGoYGOkQGEAWJBmDrGEMpI8z8A "Octave – Try It Online")
The code should be fairly obvious. Number of nonzero elements in the binary representation of each of the numbers in the range.
This would be `@(a,b)nnz(dec2bin(a:b)-48)` without the communication toolbox.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~56~~ ~~54~~ 52 bytes
~~This can be golfed more imo.~~ 
-2 Bytes thanks to Mr.Xcoder
-2 More bytes thanks to M. I. Wright
```
lambda a,b:''.join(map(bin,range(a,b+1))).count('1')
```
[Try it online!](https://tio.run/##K6gsycjPM/6fbhvzPycxNyklUSFRJ8lKXV0vKz8zTyM3sUAjKTNPpygxLz1VAyijbaipqamXnF@aV6Khbqiu@b@gKBPITNcw0THX1ORC8Cw0Nf8DAA "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 2 bytes
```
ṡb
```
[Try it online](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwi4bmhYiIsIiIsIjRcbjciXQ==) or see a [four byte flagless version](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaFiZuKIkSIsIiIsIjRcbjciXQ==).
Gets the range between the two inputs, converts each to a list of 1s and 0s, then deep flattens and sums with the `d` flag.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
çy╠Æ¼☻
```
[Run and debug it](https://staxlang.xyz/#p=8779cc92ac02&i=4+7&a=1)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 72 bytes
```
param($x,$y)$x..$y|%{$o+=([convert]::ToString($_,2)-replace0).length};$o
```
[Try it online!](https://tio.run/##BcFRCoMwDADQy2TQMi3RT8VTuD@RUSSoUJuSlU3RnT2@l/hH8lkoBNXkxW8G9gIOC7tzcFyPE/jZmWHi@CXJY9O8uM@yxtnAu6htKZSCnwitCxTnvPxbYFWtELVGvAE "PowerShell – Try It Online")
Long because of the conversion to binary `[convert]::ToString($_,2)` and getting rid of the zeros `-replace0`. Otherwise we just take the input numbers, make a range `$x..$y` and for each number in the range convert it to binary, remove the zeros, take the `.length` thereof (i.e., the number of ones remaining), and add it to our `$o`utput.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + common utilities, 50
```
jot -w%o - $@|tr 247356 1132|fold -1|paste -sd+|bc
```
[Try it online!](https://tio.run/##S0oszvj/Pyu/REG3XDVfQVdBxaGmpEjByMTc2NRMwdDQ2KgmLT8nRUHXsKYgsbgkVUG3OEW7Jin5////hgb/jQwA "Bash – Try It Online")
Converting integers to binary strings is always a bit of pain in bash. The approach here is slightly different - convert the integers to octal, then replace each octal digit with the number of binary 1s it contains. Then we can just sum all converted digits
[Answer]
# APL+WIN, ~~33~~ 26 bytes
Prompts for vector of integers:
```
+/,((↑v)⍴2)⊤(1↓v)+0,⍳-/v←⎕
```
[Try it online! Courtesy of Dalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r6@toaDxqm1im@ah3i5Hmo64lGoaP2iaXaWob6Dzq3ayrXwZUC9TzH6j6fxqXuYIJVxqXkYGCoQGYBjFALGMFQxBfwRAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
v←⎕ prompt for input of a vector of two integers max first
(v←1↓v)+0,⍳-/ create a vector of integers from min to max
(↑v)⍴2 set max power of 2 to max 
⊤ convert integers to a matrix of binaries
+/, convert matrix to a vector and sum
```
[Answer]
# [R](https://www.r-project.org/), ~~44 40~~ 37 bytes
```
function(a,b)sum(c(0,intToBits(a:b)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJs7g0VyNZw0AnM68kJN8ps6RYI9EqSVNT83@ahomOueZ/AA "R – Try It Online")
Previously:
```
function(a,b)sum(strtoi(intToBits(a:b)))
function(a,b)sum(as.integer(intToBits(a:b)))
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
⟦₂ḃᵐcọht
```
[Try it online!](https://tio.run/##ASkA1v9icmFjaHlsb2cy///in6bigoLhuIPhtZBj4buNaHT//1sxMCwyMF3/Wg "Brachylog – Try It Online")
### Explanation
```
⟦₂         Ascending range between the two elements in the input
  ḃᵐ       Map to base 2
    c      Concatenate
     ọ     Occurrences of each element
      h    Head: take the list [1, <number of occurrences of 1>]
       t   Tail: the number of occurrences of 1
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 69 bytes
```
: f 1+ 0 -rot swap do i begin 2 /mod -rot + swap ?dup 0= until loop ;
```
[Try it online!](https://tio.run/##LY3NDsIgEITvPsWk14ZK8S9poz6LilSS2t0gjY@PC3iZ@TazmXEU4ktNLltKAxz6FhoqUMTne2NYgsf9OfkFBts32Zq1Nb3alaHPWJfoZ8xEjFFaGCYH5eWALlTpGkCpSyMjx3w/wrjppZVFd6J7nDJrGF08w58KCqcf "Forth (gforth) – Try It Online")
### Explanation
The basic algorithm is to loop over every number in range, and sum the binary digits (divide by two, add remainder to sum, repeat until number is 0)
### Code Explanation
```
1+                   \ add one to the higher number to make it inclusive
0 -rot swap          \ create a sum value of 0 and put loop parameters in high low order
do                   \ start a loop over the range provided
  i                  \ place the index on the stack
  begin              \ start an indefinite loop
    2 /mod           \ get the quotient and remainder of dividing by 2
    -rot             \ move the quotient to the back
    + swap           \ add the remainder to the sum and move it down the stack
    ?dup             \ duplicate the quotient unless it equals 0
    0=               \ check if it equals 0
  until              \ if it does equal 0, end the inner loop
loop                 \ end the outer loop
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Σṁḋ…
```
[Try it online!](https://tio.run/##yygtzv7//9zihzsbH@7oftSw7P///yb/zQE "Husk – Try It Online")
### Explanation
```
Σṁḋ…
   …     Get the (inclusive) range.
 ṁḋ      Convert each to binary and concatenate.
Σ        Get the sum.
```
[Answer]
## PHP, 97 Bytes
(sure this can be shortened, but wanted to use the functions)
[**Try it online**](https://tio.run/##K8go@G9jX5BRwKWSWJReFm0Qa2tiDWUbxtqaW3PZ2wEV2BaXJhWXFMUn55fmlWhk5hbk5KekaiQWFSVWxucmFmikleYll2Tm52molGlWF6WWlBblKaSkJidlgkWsa3WKEvPSUzVgdujALNDU1NQx1LT@/x8A)
**Code**
```
<?=substr_count(implode(array_map(function($v){return decbin($v);},
 range($argv[0],$argv[1]))),1);
```
**Explanation**
```
<?=
 substr_count(   //Implode the array and count every "1"
  implode(
    array_map(function($v){return decbin($v);}, //Transform every decimal to bin
          range($argv[0],$argv[1])   //generate a range between the arguments
     )
),1);   //count "1"'s
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
import Data.Bits
a%b=sum$popCount<$>[a..b]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzymzpJgrUTXJtrg0V6Ugv8A5vzSvxEbFLjpRTy8p9n9uYmaegq1CQVFmXomCioKhgYGqhpGBgZWVZ16JpsJ/AA "Haskell – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
```
$+JTB:a\,b
```
[Try it online!](https://tio.run/##K8gs@P9fRdsrxMkqMUYn6f///4YGBv@NDAwA "Pip – Try It Online")
### Explanation
```
            a and b are command-line args (implicit)
      a\,b  Inclusive range from a to b
   TB:      Convert to binary (: forces TB's precedence down)
  J         Join into a single string of 1's and 0's
$+          Sum (fold on +)
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), ~~[40](https://codegolf.stackexchange.com/revisions/166208/1)~~ 37 bytes
```
x=>y=>str(map(bin,x..y+1)).count("1")
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@7/C1q7S1q64pEgjN7FAIykzT6dCT69S21BTUy85vzSvREPJUEnzf0FRJpCZpmGiqWGuqfkfAA "Proton – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
ＩΣ⭆…·ＮＮ⍘ι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyO4BMhP900s0MjMS84pLc4sSw1KzEtP1fDMKygt8SvNTUot0tDUUUDhAvlOicWpEL0amToKRpogYP3/vwmXxX/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
     ＮＮ     Input numbers
   …·       Inclusive range
  ⭆         Map over range and join
        ι   Current value
         ²  Literal 2
       ⍘    Convert to base as string
 Σ          Sum of digits
Ｉ           Cast to string
            Implicitly print
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~38~~ 32 bytes
```
seq -f2o%.fn $*|dc|tr -d 0|wc -c
```
*Thanks to @Cowsquack for golfing off 6 bytes!*
[Try it online!](https://tio.run/##S0oszvj/vzi1UEE3zShfVS8tT0FFqyYluaakSEE3RcGgpjxZQTf5////hgb/jQwA "Bash – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~19~~ 13 bytes
```
{+//2\x_!1+y}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpbX98opiJe0VC7svZ/WrSJtXnsfwA "K (ngn/k) – Try It Online")
`{` `}` is a function with arguments `x` and `y`
`!1+y` is the list 0 1 ... y
`x_` drops the first x elements
`2\` encodes each int as a list of binary digits of the same length (this is specific to ngn/k)
`+/` sum
`+//` sum until convergence; in this case sum of the sum of all binary digit lists
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~32~~ 30 bytes
*-1 bytes thanks to Brad Gillbert*
```
{[…](@_)>>.base(2).comb.sum}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwvzr6UcOyWA2HeE07O72kxOJUDSNNveT83CS94tLc2v/FiSCFGoYGBjoKRgYGmtZccBGQgOZ/AA "Perl 6 – Try It Online")
Explanation:
```
[…](@_)    #Range of parameter 1 to parameter 2
       >>    #Map each number to
                      .sum  #The sum of
                 .comb      #The string of
         .base(2)    #The binary form of the number
```
]