text:
Sort numbers by binary 1's count
Goal
Write a function or program sort an array of integers in descending order by the number of 1's present in their binary representation.  No secondary sort condition is necessary.
Example sorted list
(using 16-bit integers)
  Dec                Bin        1's
16375   0011111111110111        13
15342   0011101111101110        11
32425   0111111010101001        10
11746   0010110111100010         8
28436   0000110111110100         8
19944   0100110111101000         8
28943   0000011100011111         8
 3944   0000011111101000         7
15752   0011110110001000         7
  825   0000000011111001         6
21826   0101010101000010         6

Input
An array of 32-bit integers.
Output
An array of the same integers sorted as described.
Scoring
This is code golf for the least number of bytes to be selected in one week's time.

You didn't explicitly mention, but does it need to be in descending order?

You're right, I missed that.  Everyone else has gone with descending, so we'll stick with that.

I think the final number (21826) has been converted wrong. according to my Windows calculator, it's 0101 0101 0100 0010, not 0010 1010 1100 0010.

Thanks for those corrections.  That's weird about 21826 because I used Excel to convert the numbers to binary.  I wonder about the rest now.

Solution using assembly and popcount instruction?

Some CPUs have efficient opcodes for doing this, but I suspect assembly language to be a bit too verbose to win code golf. (I think Motorola 68040 had it.)

Does the sort have to be stable or not?

Am I allowed to sort the input array in-place? It is a difference of 8 characters for my solution.

Stability is not required.  I never said the input had to remain unchanged, so in-place sorting is fine.

formatted test cases please?

Similar to the Bittiest number challenge

J (11)
(\:+/"1@#:)

This is a function that takes a list:
     (\:+/"1@#:) 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
16375 15342 32425 28943 11746 28436 19944 3944 15752 825 21826

If you want to give it a name, it costs one extra character:
     f=:\:+/"1@#:
     f 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
16375 15342 32425 28943 11746 28436 19944 3944 15752 825 21826

Explanation:

\:: downwards sort on
+/: sum of
"1: each row of
#:: binary representation

@ak82 it's the ASCII version of APL

@JanDvorak of sorts; there have been quite a few changes: http://www.jsoftware.com/papers/j4apl.htm (see Language section).

There's also \:1#.#: which saves a few bytes.

JavaScript, 39
Update: Now shorter than Ruby.
x.sort(q=(x,y)=>!x|-!y||q(x&x-1,y&y-1))

40
x.sort(q=(x,y)=>x&&y?q(x&x-1,y&y-1):x-y)

Explanation:
q is a recursive function. If x or y are 0, it returns x-y (a negative number if x is zero or a positive number if y is zero). Otherwise it removes the lowest bit (x&x-1) from x and y and repeats.
Previous version (42)
x.sort(q=(x,y)=>x^y&&!x-!y+q(x&x-1,y&y-1))

This is really clever! I'm still trying to wrap my mind around it.

Shouldn't ~y work instead of -!y?

@toothbrush The ending condition is that x or y are 0, in which case the expression !x|-!y becomes non-zero. ~ doesn't really fit in since it's non-zero for many inputs (including zero)

Can anyone help me in case a secondary sorting is required, please?

Ruby 41
f=->a{a.sort_by{|n|-n.to_s(2).count(?1)}}

Test:
a = [28943, 825, 11746, 16375, 32425, 19944, 21826, 15752, 15342, 3944, 28436];
f[a]
=> [16375, 15342, 32425, 11746, 28436, 28943, 19944, 15752, 3944, 21826, 825]

Simple. Understandable. Short. Kudos for this solution.

Python 3 (44):
def f(l):l.sort(lambda n:-bin(n).count('1'))

Common Lisp, 35
logcount returns the number of ‘on’-bits in a number.  For a list l, we have:
(sort l '> :key 'logcount)

CL-USER> (sort (list 16375 15342 32425 11746 28436 19944 28943 3944 15752 825 21826) '> :key 'logcount)
;=> (16375 15342 32425 11746 28436 19944 28943 3944 15752 825 21826)

As a standalone function, and what I'll base the byte count on:
(lambda(l)(sort l'> :key'logcount))

Python 3, 90 77 72 67 characters.
Our solution takes an input from the command-line, and prints the number in descending order (67 chars), or ascending (66).
Descending order
print(sorted(input().split(),key=lambda x:-bin(int(x)).count("1"))) # 67

Thanks to @daniero, for the suggestion of using a minus in the 1's count to reverse it, instead of using a slice to reverse the array at the end! This effectively saved 5 characters.
Just for the sake of posting it, the ascending order version (which was the first we made) would take one character less.
Ascending order:
print(sorted(input().split(),key=lambda x:bin(int(x)).count("1"))) # 66

Thanks to @Bakuriu for the key=lambda x… suggestion. ;D

So 0 will always be a part of your output then; That's not correct.

I don't see anything in the question that prohibits me from inserting a value.

I do: "An array of the same integers sorted as described." ;) Besides, why not just use raw_input() and drop some characters?

@daniero fixed it. Switching to Python 3 (a Python 2 answer was already present, gotta be creative!) allows me to use input(), saving two characters (two are to be added because of the brackets required by print()).

You can drop the [] inside sorted. Also the output of this program is the number of 1s in the numbers in input sorted, but you should output the number you received in input, sorted using the number of 1s. Something like: print(sorted(input().split(), key=lambda x:bin(int(x)).count('1'))) would be correct.

@Bakuriu awesome! Thank you. Your suggestion prints values in ascending order, though, which may or may not be what the OP wants.

You can use lambda x:-bin(...  insted of [::-1], sort of like I did :)

@daniero Clever… StackOverflow teaches you how to do things properly, CodeGolf teaches you the best proper hacks. I'm glad I found this site. ;D -- For a moment I though we could use the fact that binaries contain only 0's and 1's to our advantage (if we sort by ascending order, and by the number of 0's, we get the number with the least 0's (and thus, the most 1's) first) -- but then I recalled that Python doesn't pad binary numbers with 0's…

The second argument to sorted is key, so there's no need for key= either.

Question defines input and output as an array.  So it seems there is no need parse input and print output.

JavaScript [76 bytes]
a.sort(function(x,y){r='..toString(2).split(1).length';return eval(y+r+-x+r)})

where a is an input array of numbers.
Test:
[28943,825,11746,16375,32425,19944,21826,15752,15342,3944,28436].sort(function(x, y) {
    r = '..toString(2).split(1).length';
    return eval(y + r + -x + r);
});

[16375, 15342, 32425, 19944, 11746, 28943, 28436, 15752, 3944, 21826, 825]

Could you please tell how the .. works? My understanding is that if x = 5 then eval(x + r) becomes eval(5..toString(2).match(/1/g).length) which is, I suppose, invalid. Thanks.

@GaurangTandon It is not. As you know, in JS everything except literals is an object. And numbers. So theoretically (and practically) you may get properties or call methods of any non-literal via dot notation, as you do 'string'.length or [1,2,3].pop(). In case of numbers you may do the same but you should keep in mind that after a single dot the parser will look for a fractional part of the number expecting a float value (as in 123.45). If you use an integer you should "tell" the parser that a fractional part is empty, setting an extra dot before addressing a property: 123..method().

You can save two bytes by stripping the zeros and treating the rest as a decimal number. Replace match(/1/g).length with replace(/0/g,"").

@VisioN Thanks! Learnt a new thing.

Can anyone help me in case a secondary sorting is required, please?

a.sort(function(x,y){r='..toString(2).match(/1/g).length';return eval(y+r+-x+r)})

69 Bytes a.sort((x,y)=>{f=z=>z.toString(2).replace(/0/g,"");return f(x)<f(y)}) Correct me if i'm wrong but length isn't needed if you use < instead of -

75 using same formula and version

 Mathematica 30
SortBy[#,-DigitCount[#,2,1]&]&

Usage:
SortBy[#,-DigitCount[#,2,1]&]&@
                           {19944,11746,15342,21826,825,28943,32425,16375,28436,3944,15752}

{16375, 15342, 32425, 11746, 19944, 28436, 28943, 3944, 15752, 825,
  21826}

k [15 Chars]
{x@|<+/'0b\:'x}

Example 1
{x@|<+/'0b\:'x}19944, 11746, 15342, 21826, 825, 28943, 32425, 16375, 28436, 3944, 15752

16375 15342 32425 28436 28943 11746 19944 15752 3944 825 21826

Example 2 (all numbers are 2^n -1)
{x@|<{+/0b\:x}'x}3 7 15 31 63 127

127 63 31 15 7 3

Java 8 - 87/113 81/111 60/80 60/74/48 characters
This is not a complete java program, it is just a function (a method, to be exact).
It assumes that java.util.List and java.lang.Long.bitCount are imported, and has 60 characters:
void s(List<Long>a){a.sort((x,y)->bitCount(x)-bitCount(y));}

If no pre-imported stuff are allowed, here it is with 74 characters:
void s(java.util.List<Long>a){a.sort((x,y)->x.bitCount(x)-x.bitCount(y));}

Add more 7 characters if it would be required that it should be static.
[4 years later] Or if you prefer, it could be a lambda (thanks @KevinCruijssen for the suggestion), with 48 bytes:
a->{a.sort((x,y)->x.bitCount(x)-x.bitCount(y));}

Any reason why you can't do Integer.bitCount(x)<Integer.bitCount(y)?-1:1;? Do you need the -1,0,1 behavior?

Also, is it possible to replace the <Integer> with space?

You can also use Long, that save some space :)

Also   a.sort((x,y)->Long.bitCount(x)-Long.bitCount(y));

@Quincunx comparator needs to return 0 when bitcounts are the same (by contract)

@Quincunx. Yes, I needed the -1,0,1 behaviour, but by using - as suggested by RobAu, it gets smaller. And really need the <Long> (was <Integer>). Otherwise I screw the compiler type inference and get a compile error.

@RobAu Thanks, I should have seen those obvious shortcuts.

Realistically, this is a function because it doesn't leverage the this reference or any of this's variables. So while technically a method because it -could-, it doesn't; I would personally call this a function. (This is reinforced by the fact that you could, as you state, make it static. Static method === function.)

I have a complete 150 char java 8 solution. http://codegolf.stackexchange.com/a/22064/7981

I know it's been 4 years, but you can golf Long.bitCount to x.bitCount in your version without pre-imported stuff (not sure how it was four years ago, but imports are counted towards the byte-count these days). Also, since you've specified Java 8, you can change void s(java.util.List<Long>a) to a->. Try it online - 48 bytes Nice answer though, +1 from me.

@KevinCruijssen I don't remember this puzzle, since as you already said, it was 4 years since then. However, I'm not sure if a lambda expression with a inferred parameter type depending on an ommited context would be acceptable. Anyway, I added it to the answer, thanks.

@VictorStafusa Well, it is acceptable these days, but I also don't know about four years ago when this challenge was posted. Btw, in the 80-byte version you can still golf Long.bitCount to x.bitCount, since you've already specified x is a Long in the java.util.List<Long>a parameter.

@KevinCruijssen Thanks. I'm so used that using a variable instance to call a static method is a bad practice that I ever forgot that the compiler accepts that.

Mathematica 39
IntegerDigits[#,2] converts a base 10 number to list of 1's and 0's.
Tr sums the digits.
f@n_:=SortBy[n,-Tr@IntegerDigits[#,2]&]

Test Case
f[{19944, 11746, 15342, 21826, 825, 28943, 32425, 16375, 28436, 3944, 15752}]

{16375, 15342, 32425, 11746, 19944, 28436, 28943, 3944, 15752, 825, 21826}

I've grown fond of that (ab?)use of Tr[] in golfing code.

Python 2.x - 65 characters (bytes)
print sorted(input(),key=lambda x:-sum(int(d)for d in bin(x)[2:]))

That's actually 66 characters, 65 if we make it a function (then you need something to call it which is lamer to present).
f=lambda a:sorted(a,key=lambda x:-sum(int(d)for d in bin(x)[2:]))

Demo in Bash/CMD:
echo [16, 10, 7, 255, 65536, 5] | python -c "print sorted(input(),key=lambda x:-sum(int(d)for d in bin(x)[2:]))"

you can change sum(int(d)for d in bin(x)[2:]) to sum(map(int,bin(x)[2:]))

or even: print sorted(input(),key=lambda x:-bin(x).count('1'))

Matlab, 34
Input in 'a'
[~,i]=sort(-sum(dec2bin(a)'));a(i)

Works for nonnegative numbers.

C - 85 bytes (108 106 bytes)
Portable version on GCC/Clang/wherever __builtin_popcount is available (106 bytes):
#define p-__builtin_popcount(
c(int*a,int*b){return p*b)-p*a);}
void s(int*n,int l){qsort(n,l,sizeof l,c);}

Ultra-condensed, non-portable, barely functional MSVC-only version (85 bytes):
#define p __popcnt
c(int*a,int*b){return p(*b)-p(*a);}
s(int*n,int l){qsort(n,l,4,c);}         /* or 8 as needed */

First newline included in byte count because of the #define, the others are not necessary.
Function to call is s(array, length) according to specifications.
Can hardcode the sizeof in  the portable version to save another 7 characters, like a few  other C answers did. I'm not sure which one is worth the most in terms of length-usability ratio, you decide.

sizeof l saves a byte. The horribly ugly #define p-__builtin_popcount( can help save another one.

@ugoren Thanks for the tips! The preprocessor one is such a hack, I had no idea such a thing was possible. Sadly it does not work on MSVC, but every byte counts!

58 bytes

PowerShell v3, 61 58 53
$args|sort{while($_){if($_-band1){1};$_=$_-shr1}}-des

The ScriptBlock for the Sort-Object cmdlet returns an array of 1's for each 1 in the binary representation of the number. Sort-Object sorts the list based on the length of the array returned for each number.
To execute:
script.ps1 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944

it's work. How it work? How the magic '.' comes to 'based on the length of the array'?

The '.' executes the scriptblock that comes after it. The sort command sorts based on the output of the outer scriptblock. I realize now that the inner scriptblock is not needed. see edit

$f={ is redundant, while -> for, -band1-> %2, -des->-d and other golf tricks. It's clear. Can you explain how to work $args|sort{@(1,1,...,1)}? It's work! How the sort compares arrays without explicit .Count? where to read about it? Thanks!

@mazzy, you're right, I removed the redundant bits now. It's the default sorting of the Sort-Object cmdlet. See: help Sort-Object -Parameter property I don't know where the default sorting property for types is defined, but for arrays it is Count or Length.

Good guess. But $args|sort{while($_){if($_-band1){$_};$_=$_-shr1}}-des gives a wrong result. Therefore, it is not Count. It's very interesting. Thanks again.

ECMAScript 6, 61
Assumes z is the input
z.sort((a,b)=>{c=d=e=0;while(++c<32)d+=a>>c&1,e+=b>>c&1},e-d)

Test data
[28943,825,11746,16375,32425,19944,21826,15752,15342,3944,28436].sort(
    (a,b)=>{
        c=d=e=0;
        while(++c<32)
            d+=a>>c&1,e+=b>>c&1
    },e-d
)

[16375, 15342, 32425, 11746, 19944, 28436, 28943, 15752, 3944, 21826, 825]

Thanks, toothbrush for the shorter solution.

I've just tried your solution, but it didn't work. It doesn't sort the numbers.

@toothbrush woops. Thanks for catching that, should work now.

Great work! I like it.

Only 61 bytes: z.sort((a,b)=>{c=d=e=0;while(++c<32)d+=a>>c&1,e+=b>>c&1},e-d) (and thanks for the up-vote).

My solution is now the same size as yours!

R, 132 96 94 88 84 75 73 53 51 bytes
-20 thanks to J.Doe's implementation
-2 more thanks to Giuseppe

function(x)x[order(colSums(sapply(x,intToBits)<1))]

My original post:
pryr::f(rev(x[order(sapply(x,function(y)sum(as.double(intToBits(y)))))]))

Try it online!
I tried several different methods before I got down to this result.
Matrix Method: Created a two column matrix, one column with the input vector, one of the sum of the binary representation, then I sorted on the sum of binary.
function(x){m=matrix(c(x,colSums(sapply(x,function(y){as.integer(intToBits(y))}))),nc=2,nr=length(x));m[order(m[,2],decreasing=T),]}

Non-Matrix: Realized I could toss out the matrix function and instead create a vector of binary values, sum them, order them, then use the ordered values to reorder the input vector.
function(x){m=colSums(sapply(x,function(y){as.integer(intToBits(y))}));x[order(m,decreasing=T)]}

Minor Changes
function(x){m=colSums(sapply(x,function(y)as.double(intToBits(y))));x[order(m,decreasing=T)]}

More Minor Changes Converting entire thing to one line of code instead of two separated by a semicolon.
function(x)x[order(colSums(sapply(x,function(y)as.double(intToBits(y)))),decreasing=T)]

Sum Method Instead of adding the columns with colSums of the binary matrix created by sapply, I added the elements in the column before sapply "finished."
function(x)x[order(sapply(x,function(y)sum(as.double(intToBits(y)))),decreasing=T)]

Decreasing to Rev I really wanted to shorten decreasing, but R squawks at me if I try to shorten decreasing in the order function, which was necessary to get the order desired as order defaults to increasing, then I remembered the rev function to reverse a vector. EUREKA!!! The last change in the final solution was function to pryr::f to save 2 more bytes
function(x)rev(x[order(sapply(x,function(y)sum(as.double(intToBits(y)))))])

53 bytes

51 bytes improving on @J.Doe 's excellent golf!

Haskell, 123C
import Data.List
import Data.Ord
b 0=[]
b n=mod n 2:b(div n 2)
c n=(n,(sum.b)n)
q x=map fst$sortBy(comparing snd)(map c x)

This is the first way I thought of solving this, but I bet there's a better way to do it. Also, if anyone knows of a way of golfing Haskell imports, I would be very interested to hear it.
Example
*Main> q [4,2,15,5,3]
[4,2,5,3,15]
*Main> q [7,0,2]
[0,2,7]

Ungolfed version (with explanations)
import Data.List
import Data.Ord

-- Converts an integer into a list of its bits
binary 0 = []
binary n = mod n 2 : binary (div n 2)

-- Creates a tuple where the first element is the number and the second element
-- is the sum of its bits.
createTuple n = (n, (sum.binary) n)

-- 1) Turns the list x into tuples
-- 2) Sorts the list of tuples by its second element (bit sum)
-- 3) Pulls the original number out of each tuple
question x = map fst $ sortBy (comparing snd) (map createTuple x)

would it be helpful to use the infix notation for mod, n`mod`2? It  has the same precedence as multiplication and division.

That wouldn't be too helpful for golfing reasons as far as I can see. I'd lose two spaces, but gain two backticks, right?

import Data.List;import Data.Ord;import Data.Bits;q=sortBy(comparing popCount) - 80C - or using your approach, import Data.List;import Data.Ord;b 0=0;b n=(mod n 2)+b(div n 2);q=sortBy(comparing b) - 86C

I tried avoiding imports entirely, best I could manage was 87C by golfing quicksort: b 0=0;b n=mod n 2+b(div n 2);q[]=[];q(a:c)=f((b a>).b)c++a:f((b a<=).b)c;f=(q.).filter

Julia 1.0, 41 bytes
a->sort(a,by=x->sum((x>>n)&1 for n=0:63))

Try it online!

Firstly, you can use two argument sum, like this: sum(n->x>>n&1,0:63). Secondly, by=count_ones is even shorter

Also, shorter than two argument sum is: sum(x.>>(0:63).&1))

DFSORT (IBM Mainframe sorting product) 288 (each source line is 72 characters, must have space in position one)
 INREC IFTHEN=(WHEN=INIT,BUILD=(1,2,1,2,TRAN=BIT)),
       IFTHEN=(WHEN=INIT,FINDREP=(STARTPOS=3,INOUT=(C'0',C'')))
 SORT FIELDS=(3,16,CH,D)
 OUTREC BUILD=(1,2)

Just for fun, and no mathematics.
Takes a file (could be executed from a program which used an "array") with the integers. Before sorting, it translates the integers to bits (in a 16-character field). Then changes the 0s in the bits to nothing. SORT Descending on the result of the changed bits. Creates the sorted file with just the integers.

Smalltalk (Smalltalk/X), 36 (or maybe 24)
input in a; destructively sorts in a:
a sort:[:a :b|a bitCount>b bitCount]

functional version: returns a new sorted array:
a sorted:[:a :b|a bitCount>b bitCount]

there is even a shorter variant (passing the name or the function as argument) in 24 chars.
But (sigh) it will sort highest last. As I understood, this was not asked for, so I don't take that as golf score:
a sortBySelector:#bitCount

CoffeeScript (94)
Readable code (212):
sort_by_ones_count = (numbers) ->
  numbers.sort (a, b) ->
    a1 = a.toString(2).match(/1/g).length
    b1 = b.toString(2).match(/1/g).length
    if a1 == b1
      0
    else if a1 > b1
      1
    else
      -1

console.log sort_by_ones_count [825, 3944, 11746, 15342, 15752, 16375, 19944, 21826, 28436, 28943, 32425]

Optimized (213):
count_ones = (number) -> number.toString(2).match(/1/g).length
sort_by_ones_count = (numbers) -> numbers.sort (a, b) ->
  a1 = count_ones(a)
  b1 = count_ones(b)
  if a1 == b1 then 0 else if a1 > b1 then 1 else -1

Obfuscating (147):
c = (n) -> n.toString(2).match(/1/g).length
s = (n) -> n.sort (a, b) ->
  a1 = c(a)
  b1 = c(b)
  if a1 == b1 then 0 else if a1 > b1 then 1 else -1

Ternary operators are excessively long (129):
c = (n) -> n.toString(2).match(/1/g).length
s = (n) -> n.sort (a, b) ->
  a1 = c(a)
  b1 = c(b)
  (0+(a1!=b1))*(-1)**(0+(a1>=b1))

Too long yet, stop casting (121):
c = (n) -> n.toString(2).match(/1/g).length
s = (n) -> n.sort (a, b) ->
  a1 = c(a)
  b1 = c(b)
  (-1)**(a1>=b1)*(a1!=b1)

Final (94):
c=(n)->n.toString(2).match(/1/g).length
s=(n)->n.sort((a, b)->(-1)**(c(a)>=c(b))*(c(a)!=c(b)))

Scala, 58
def c(l:List[Int])=l.sortBy(-_.toBinaryString.count(_>48))

PHP 5.4+ 131
I don't even know why I bother with PHP, in this case:
<?unset($argv[0]);usort($argv,function($a,$b){return strcmp(strtr(decbin($b),[0=>'']),strtr(decbin($a),[0=>'']));});print_r($argv);

Usage:
> php -f sortbybinaryones.php 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
Array
(
    [0] => 16375
    [1] => 15342
    [2] => 32425
    [3] => 28436
    [4] => 19944
    [5] => 11746
    [6] => 28943
    [7] => 3944
    [8] => 15752
    [9] => 825
    [10] => 21826
)

well, someone has to bother with PHP

C
void main()
{
 int a[]={7,6,15,16};
 int b,i,n=0;
 for(i=0;i<4;i++)
 {  for(b=0,n=0;b<=sizeof(int);b++)
      (a[i]&(1<<b))?n++:n;
    a[i]=n;
 }
 for (i = 1; i < 4; i++)
  {   int tmp = a[i];
      for (n = i; n >= 1 && tmp < a[n-1]; n--)
         a[n] = a[n-1];
      a[n] = tmp;
  }
}

Since this is a code golf competition, you should try to shorten your code.

C#, 88 89
int[] b(int[] a){return a.OrderBy(i=>-Convert.ToString(i,2).Count(c=>c=='1')).ToArray();}

Edit: descending order adds a character.

ECMAScript 6 (61 characters):
_=_=>_.toString(2).replace(/0/g,'');x.sort((a,b)=>_(b)-_(a))

Expects the input array to be in x.

Javascript 84
Inspired by other javascript answers, but without eval and regex.
var r=(x)=>(+x).toString(2).split('').reduce((p,c)=>p+ +c)
[28943,825,11746,16375,32425,19944,21826,15752,15342,3944,28436].sort((x,y)=>r(x)-r(y));

The question is code golf, please try to 'golf' your code: remove unnecessary whitespace and try to make your code as small as possible. Also, include a character count in your answer.

C - 124 111
Implemented as a method and using the standard library for the sorting. A pointer to the array and the size should be passed as parameters. This will only work on systems with 32-bit pointers. On 64-bit systems, some characters have to be spent specifying pointer definitions.
Indentation for readability
c(int*a,int*b){
    int d,e,i;
    for(d=e=i=0;i-32;){
        d+=*a>>i&1;e+=*b>>i++&1;
    }
    return d>e?-1:d<e;
}
o(r,s){qsort(r,s,4,c);}

Sample call:
main() {
    static int a[] ={1, 2, 3, 4, 5, 6, 7, 8, 9};
    o(a, 9);
}

Javascript (82)
a.sort(function(b,c){q=0;while(b|c){b%2?c%2?0:q++:c%2?q--:0;b>>=1;c>>=1}return q})

Postscript, 126
Because list of values by which we sort is known beforehand and very limited (32), this task can be easily done even if there's no built-in for sorting, by picking matching values for 1..32. (Is it O(32n)? Probably).
Procedure expects array on stack and returns 'sorted' array.
/sort_by_bit_count {
    [ exch
    32 -1 1 {
        1 index
        {
            dup 2 32 string cvrs
            0 exch
            {48 sub add} forall
            2 index eq
            {3 1 roll} {pop} ifelse
        } forall
        pop
    } for
    pop ]
} def

Or, ritually stripped of white space and readability:
/s{[exch 32 -1 1{1 index{dup 2 32 string cvrs 0 exch{48 sub add}forall 2 index eq{3 1 roll}{pop}ifelse}forall pop}for pop]}def

Then, if saved to bits.ps it can be used like this:
gs -q -dBATCH bits.ps -c '[(%stdin)(r)file 1000 string readline pop cvx exec] s =='
825 3944 11746 15342 15752 16375 19944 21826 28436 28943 32425
[16375 15342 32425 11746 19944 28436 28943 3944 15752 825 21826]

I think it effectively is the same as this Perl (there's yet no Perl here, too):
sub f{map{$i=$_;grep{$i==(()=(sprintf'%b',$_)=~/1/g)}@_}reverse 1..32}

Though that, unlike Postscript, can be easily golfed:
sub f{sort{j($b)-j($a)}@_}sub j{$_=sprintf'%b',@_;()=/1/g}

Postscript! My first love, my favorite language of all time! It is nice to see another believer in the One True Programming Language.

Java 8: 144
static void main(String[]a){System.out.print(Stream.of(a).mapToInt(Integer::decode).sorted(Comparable.comparing(Integer::bitCount)).toArray());}

In expanded form:
static void main(String[] args){
    System.out.print(
        Stream.of(args).mapToInt(Integer::decode)
              .sorted(Comparable.comparing(Integer::bitCount))
              .toArray()
        );
}

As you can see, this works by converting the args to a Stream<String>, then converting to a Stream<Integer> with the Integer::decode function reference (shorter than parseInt or valueOf), and then sorting by Integer::bitCount, then putting it in an array, and printing it out.
Streams make everything easier.

PowerShell v2 or later, 44
sort{[convert]::ToString($_,2)-replace0}-des

The long version:
Sort-Object -Property {[convert]::ToString($_, 2) -replace '0', ''} -Descending

"sort" is a default alias for the Sort-Object cmdlet.
Sort-Object allows sorting the incoming list by evaluating an expression on the fly, which is the script block inside the curly braces.
The .NET class "Convert" is used to convert the incoming integer ("$_") into its binary string representation.
The "-replace" Operator will then remove all zeros, so that only a string of ones remains (the string "Replace()" method would have worked, too, but would have been longer).
Since these strings all consist of the same character, they'll be sorted by length, ascending by default. The switch argument "Descending" will reverse the order, and since there's another argument 'Debug', the first three characters are required for PowerShell to identify the switch.
The list to sort is expected in the pipeline/stdin, for example:
$l = 15342, 28943, 16375, 3944, 11746, 825, 32425, 28436, 21826, 15752, 19944
$l | sort{[convert]::ToString($_,2)-replace0}-des

Sort-Object
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/sort-object?view=powershell-6
Convert Class
https://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx

Welcome to PPCG!

It's a code snippet, not function or program. Sorry.

05AB1E, 4 bytes
ΣbSO

Try it online!

4-byte alternative which is a literal translation of the title: Σb1¢ (Σort numbers by binary 1s ¢ount) :) (Bit of a weird s in sort though.. ;p)

I don't think this is in descending order.

Perl 6, 27 bytes
*.sort(-*.base(2).comb.sum)

Try it online!

Alternatively, .comb(~1)

C#, 191 183 172 thanks to Rik
 using System.Linq;class P{static void Main(string[]a){System.Console.WriteLine(string.Join(" ",a.Select(int.Parse).OrderBy(v=>{int c=0;for(;v>0;c++,v&=v-1);return-c;})));}}

Formatted:
using System.Linq;
class P
{
    static void Main(string[] a)
    {
        System.Console.WriteLine(string.Join(" ", a.Select(int.Parse)
            .OrderBy(v => {
                int c = 0;
                for (; v > 0; c++, v &= v - 1);
                return -c;
            })
        ));
    }
}

When run as foo.exe 32425 28943 28436 21826 19944 16375 15752 15342 11746  3944 825 the output is:
16375 15342 32425 28943 28436 19944 11746 15752 3944 21826 825

Including the bitcount:
16375   13
15342   11
32425   10
28943   8
28436   8
19944   8
11746   8
15752   7
3944    7
21826   6
825     5

As function only: 100 89 chars
...Which some seem to regard as correct too:
int[] v(int[]a){return a.OrderBy(v=>{int c=0;for(;v>0;c++,v&=v-1);return-c;}).ToArray();}

To use, call v() with an array of ints to be sorted by binary 1's count.

instead of OrderByDescending you can use OrderBy and return -c in your lambda and save 9 chars.

D'oh! Thanks! Why didn't I think of that?! :D Actually, it saves 10 since I don't need a space between return and -c :D

C++ and QT
template<typename T>

//Compars the number of ones in the binary representation of some numbers
bool onesCountSort()(Const T* a, const T* b) const
{
   int aCount = getOnesCount(&a);
   int bCount = getOnesCount(&b);
   return aCount < bCount;
}

//Returns the number of ones in a number
int getOnesCount(T value) const
{
    int rVal = 0;
    while(value > 0)
    {
       rVal++;
       value = value >> 1;
    }
    return rVal;
}

int main(int argc, char *argv[])
{
   QList<int> listTest;
   listTest << 16375;
   listTest << 15342;
   listTest << 32425;
   listTest << 11746;
   listTest << 28436;
   //...

   qSort(list.begin(); list.end(), onesCountSort<int>());//Sort by binary ones count
   qSort(list.end(); list.begin(), onesCountSort<int>());//Reverse the sort
}

Edit:
template<typename T>

//Compars the number of ones in the binary representation of some numbers
bool onesCountSort()(Const T* a, const T* b) const
{
   return getOnesCount(a) < getOnesCount(b);
}

int getOnesCount(const T* value, int count = 0) const
{
    return &value ? count : getOnesCount(value >> 1, count + 1);
}

GolfScript, 14 chars
~{2base 0-,}$`

Example input (sorted in numerical order):
[825 3944 11746 15342 15752 16375 19944 21826 28436 28943 32425]

Example output (sorted by bit count) for the input above:
[825 21826 15752 3944 28436 28943 19944 11746 32425 15342 16375]

Note that the program above sorts the input in ascending order by bit count.  If you insist on descending order, that'll cost one extra char:
~{2base 0-,~}$`

Explanation:

~ evals the input. Since you didn't specify the input format, I took the liberty of assuming that the input is provided as a GolfScript array literal (i.e. a series of whitespace-separated numbers wrapped in [ ]).
{ }$ applies the code inside the braces to each element of the array, and sorts them according to the resulting sort keys.

Inside the braces, 2base uses the built-in base conversion operator to turn the number into an array of bits (e.g. 19 → [1 0 0 1 1]). The 0- then removes all the zero bits from the array (the space before it is needed to keep base0 from being parsed as a single token) and the , counts the length of the remaining array.
(In the descending order version, the ~ then bitwise negates the count, effectively applying the map x ↦ −(x + 1) and thus inverting the sort order.)

Finally, the ` un-evals the sorted array, converting it back into the input format for output.

**
C++(Visual Studio 2013), 112
**
#define n int
#define s __popcnt
n* d(n i[], n l){sort(i, i+l, [](n a, n b){return  s(a) > s(b); });return i;}

Unobfuscated:
#define n int
#define s __popcnt
n* d(n i[], n l){
    std::sort(i, i+l, [](n a, n b){return  s(a) > s(b); });
    return i;
}

haven't touched C++ for a while. While not the shortest, it PROBABLY is the fastest, by far, though it depends highly if the __popcnt is implemented as single CPU instruction, or set.
I might fire up mathbrain later and see if it's possible to compare two numbers by bits and see which one has more bits set(without any string conversions or bit counting). I think there is some kind of bit-hack that can be used, but it's probably longer.

C : 112
C(a){int c=a!=0;while(a&=a-1)c++;return c;}
B(int*a,int*b){return C(*b)-C(*a);}
S(int*a,int n){qsort(a,n,4,B);}

works on gcc with Target: x86_64-linux-gnu
usage: S(array, size);

similar to @albeert's answer, which I only saw after I completed this...

S(n,int*a) doesn't compile. Even when fixed, doesn't work on by 64bit Linux with gcc. Omitting return from C is very fragile.

Ah, you're right. I missed the compiler error among the warnings and got the same output as the previous run, so I assumed it was good. I went back to my last working version: +12 char.

57 bytes

Haskell - 107100 (including sample list and main call) else 100-22=78
import Data.List
b 0=0
b n=mod n 2+b(div n 2)
c q=map snd$ sort$ zip(map b q)q
main=print$ c [1..100]

Result:
[1,2,4,8,16,32,64,3,5,6,9,10,12,17,18,20,24,33,34,36,40,48,65,66,68,72,80,96,7,11,13,14,19,21,22,25,26,28,35,37,38,41,42,44,49,50,52,56,67,69,70,73,74,76,81,82,84,88,97,98,100,15,23,27,29,30,39,43,45,46,51,53,54,57,58,60,71,75,77,78,83,85,86,89,90,92,99,31,47,55,59,61,62,79,87,91,93,94,63,95]

C, 95 chars
Call s(array, size) to sort an array.
The framework is based on AShelly's answer, with a different bit count function.
Only works on 32bit platforms.
c(unsigned a){return a?a%2+c(a/2):0;}
f(int*a,int*b){return c(*b)-c(*a);}
s(a,n){qsort(a,n,4,f);}

The bit count function treats the numbers as unsigned, so division will discard the low bit.

php 5.3, 117 109
Thank to @mniip to point out some more char save. So New One are
usort($a,function($u,$v){return $u==$v?0:(substr_count(decbin($u),'1')<substr_count(decbin($v),'1')?1:-1);});

Older One
usort($a,function($u,$v){if($u==$v)return 0;return substr_count(decbin($u),'1')<substr_count(decbin($v),'1')?1:-1;});

I'm pretty sure you can save a few chars if you combine your return statements into one using ternary operator

K, 14
{x@>+/'0b\:'x}

.
k){x@>+/'0b\:'x} 28943 16375 15342
16375 15342 28943

C# 95
int[]o(int[]d){return d.OrderByDescending(v =>Convert.ToString(v,2).Sum(c =>c-'0')).ToArray();}

Javascript (ECMAScript 6) - 41 Characters
Takes an array a as input:
a.sort(ພ=(ຟ,ຝ)=>ຟ*ຝ?ພ(ຟ&ຟ-1,ຝ&ຝ-1):(ຝ-ຟ))

Testing (with less obfuscated code):
JSFIDDLE
a=[19944, 11746, 15342, 21826, 825, 28943, 32425, 16375, 28436, 3944, 15752];
a.sort(_=(b,c)=>b*c?_(b&b-1,c&c-1):(c-b))
console.log(a.toString());

Gives this output:
16375,15342,32425,19944,11746,28943,28436,3944,15752,21826,825

C# - 98
C# can't really compete in "the smallest" category. Still fun, though :)
x.Select(i=>new{v=i,c=Convert.ToString(i,2).Count(c=>c=='1')}).OrderByDescending(a=>a.c);

Used:
var y = new [] {28943, 825, 11746, 16375, 32425, 19944, 21826, 15752, 15342, 3944, 28436}.Select(i=>new{v=i,c=Convert.ToString(i,2).Count(c=>c=='1')}).OrderByDescending(a=>a.c);
Console.WriteLine(y.Select(a => a.v.ToString()).Aggregate((s1,s2)=>s1+","+s2));

Result:
16375,15342,32425,28943,11746,19944,28436,15752,3944,825,21826

EDIT: .NetFiddle - http://dotnetfiddle.net/ahMMbq

Longwinded C#:
using System;

namespace P
{
    class P
    {
        static int T(int v) { int i = 0; while (v != 0) { i += (v & 1); v >>= 1; } return i; }
        static int[] S(int[] a)
        { Array.Sort<int>(a, (x, y) => { return (T(x) > T(y)) ? -1 : (T(x) < T(y)) ? 0 : 1; }); return a; }
        static void Main(string[] args)
        {
            foreach (var i in S(new int[]{ 28943, 825, 11746, 16375, 32425, 19944, 21826, 15752, 15342, 3944, 28436 }))
                Console.WriteLine("{0}\t{1}\t{2}", i, Convert.ToString(i, 2), T(i));
            Console.ReadKey();
        }
    }
}

Perl, 56 bytes
sub x{$_=sprintf'%b',@_;s/1//g}print sort{x($b)<=>x$a}<>

Input is expected in STDIN, one integer per line. Output is in descending order.
sprintf '%b' converts the number into binary representation. s/1// replaces the 1, the return value is the number of replacements. Thus function x returns the number of 1 in the binary representation of the number. The sorting function sorts the number according to their binary 1's count. By exchanging $a and $b the sorting order is reversed to ascending.

PHP - 89 bytes
Here is the best I have been able to do so far.
function f($a){usort($a,function($a,$b){$c=gmp_popcount;return$c($a)<$c($b);});return$a;}

If I am allowed to sort the array in-place (which is idiomatic for PHP), then it is only 81:
function f(&$a){usort($a,function($a,$b){$c=gmp_popcount;return$c($a)<$c($b);});}

requires gmp library, which is neither in the default built nor activated by default. (see http://php.net/manual/gmp.installation.php)

Japt, 7 bytes
ñ_¤è1Ãw

Test it

Explanation
Implicit input of array U.
ñ_   Ã

Sort (ñ) by passing each element through a function.
¤

Convert to base 2 string.
è1

Count the number of 1s.
w

Reverse and implicitly output the resulting array.

Alternatives
ñ_¤o1Ãw
ñ_¤kTÃw

You need descending sort, not ascending.

Another alternative I believe would be ñ_¤è1 n. Don't think that'd be shorter combined with the other alternative, but you never know...

Javascript
- Lengthy but result is according to my expectation
- sorting numbers in ascending order according to number of binary 1s in them. If binary 1s are equal then sorting done on the base of decimal ascending order.
Thumbs up if anybody can improve or give shorter solution in javascript
  function sortNumberByBinary1s(numbers){
      //sort numbers first
      numbers=numbers.sort();
      console.log(numbers,'numbers');

      //2dimenstional array to store original number and its binary 1s
      var binNumArr = [];
      //loop to count binary 1s in each number
      for(i=0;i<numbers.length;i++){
        var num = numbers[i];
        // var binNum = Number(num.toString(2));

        let binary1 = 0;
        do if(num&1) binary1++;
        while(num>>=1);

        //store original number and its binary 1s in 2dimenstional array
        binNumArr[numbers[i]]={'number':numbers[i],'binary1':binary1};

      }

    //sort binNumArr (22dimenstional array by Number value)
    //filter(() => true) to remove empty values
      var byNumSortedArray=binNumArr.sort(function(a, b){return a.number - b.number}).filter(() => true);

      //sort byNumberSorted array by binary1 value
      var byBinary1SortedArray=byNumSortedArray.sort(function(a, b){return a.binary1 - b.binary1});

      console.log(byBinary1SortedArray,'byBinary1SortedArray');

    //get only sortedNumbers from array and return result
      var sortedNumbers=[]
      for(i=0;i<byBinary1SortedArray.length;i++){
        try{
          var number = byBinary1SortedArray[i].number;
        }catch(e){
          console.log(e,'error');
        }
        console.log(number,'number');
        sortedNumbers[i]=number;

      }
      console.log(sortedNumbers,'sortedNumbers array');
      return sortedNumbers;

    }

Input: [3,4,5,6,7,8]
  sortNumberByBinary1s([3,4,5,6,7,8]);

{number: 4, binary1: 1}
{number: 8, binary1: 1}
{number: 3, binary1: 2}
{number: 5, binary1: 2}
{number: 6, binary1: 2}
{number: 7, binary1: 3}

Output: [4, 8, 3, 5, 6, 7]

Welcome to the site! This is a code golf challenge, so you should aim to minimise your code as much as possible, starting with removing all comments and changing variable names to a single letter

Stax, 6 bytes
╖a☻║B⌡

Run and debug it at staxlang.xyz!
This will output the Unicode characters in a string. Add $ at the end (or step through execution) to see decimal.
Unpacked (7 bytes) and Explanation
{:B|+or
{          Begin block.
 :B          Convert to binary array. Ex: 11746 -> [1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0]
   |+        Sum.
     o     Terminate block and use it to sort array (ascending).
      r    Reverse. Implicit print.

Before descending order was specified in the question, there was a 6-byte unpacked solution. This is short enough that packing (into ÇÄì¬♥#) changed nothing:
{:B|+o

Run and debug it at staxlang.xyz!

K (ngn/k), 11 10 bytes
{x@>+/2\x}

Try it online!

Haskell, 57 54 bytes
-3 bytes thanks to Laikoni! (making the counting function pointfree by using the fact that we only need to support 32bit ints)
sortOn$sum.(mapM(pure[0,1])[1..32]!!)
import Data.List

Try it online!
Explanation
The function call sortOn f xs returns xs :: [x] sorted by comparing ys = map (f :: x -> y) xs where the type y has to be an instance of Ord, so we just need to feed it a function that counts the number of 1-bits:
(sum . mapM (const [0,1]) [1..32] !!)

The expression mapM (const [0,1]) [1..n] generates all the sequences of [0,1] with length n (n = 32 is sufficient since we only need to handle 32bit ints) in the right order, so we just need to index into these and take it's sum.
Example: mapM (const [0,1]) [1..2] !! 1 ≡ [[0,0],[0,1],[1,0],[1,1]] !! 2 ≡ [0,1]

As the challenge only requires 32-bit integers, this could be shortened to sortOn$sum.(mapM(pure[0,1])[1..32]!!) while losing higher number support. Btw. nice workaround with #define on TIO.

Kotlin, 57 44 bytes
{it.sortedBy{-it.toString(2).sumBy{it-'0'}}}

Try it online!

MathGolf, 5 bytes
á{âΣ~

Try it online!
Explanation:
á{âΣ~
á{     Sort by the
    ~  Negative
   Σ   Digit sum
  â    Of the number converted to binary

Powershell, 40 45 bytes
$args|sort{for(;$_;$_=$_-shr1){$s+=$_%2}$s}-d

Explanation:
Sort all arguments from the predefined $args in a descendant order by sum of bits $s.
Note: The script uses -shr1 instead /2 because a Powershell does not provide integer div.
Test script:
$f = {

$args|sort{for(;$_;$_=$_-shr1){$s+=$_%2}$s}-d

}

&$f 0 1 3 4
&$f 16375 15342 32425 11746 28436 19944 28943 3944 15752 825 21826

Output:
3
0
4
1
16375
15342
32425
19944
28943
11746
28436
15752
3944
21826
825

Factor, 31 bytes
[ [ bit-count ] inv-sort-with ]

Try it online!

Rust, 36 bytes
|s|s.sort_by_key(|n|n.count_zeros())

Try it online!
Modifies the input slice in place. It works by sorting the array by the number of zeros. Another 36 byte solution:
|s|s.sort_by_key(|n|!n.count_ones())

Try it online!
This one sorts by the bitwise negation of the number of ones.

Pyth, 12 bytes
o_/.BsN"1"cw

Try it online!
explanation:
               print(
o                sorted(
           w       input()
          c        .split()
                 , key = lambda N:
 _                 -
   .B              bin(
     s               int(
      N                N
                     )
                   )
  /                .count(
       "1"           "1"
                   )
                 )
               )

i'm aware there already is a Pyth answer, i just wanted to take a crack at it myself

Vyxal, 6 4 bytes
µb∑⌐

Try it Online!
Explained
µb∑⌐
µ     # lambda
 b    # binary
  ∑   # sum (basically adds everything inside the binary, which is equivalent to the number of 1's
   ⌐  # reverse

Zsh, 72 bytes
(for i;<<<${#${(M)${(s::)$((i<0?[##2]2**32+i:[##2]i))}#1}}\ $i)|sort -rn

Try it online!

Whoa, I had no idea zsh could do this.

This solution also does two's complement arithmetic to handle negative integers. Most other solutions don't handle -4 correctly!!! (But this challenge is too old to make too much fuss about it)

Never too old to make a fuss :)

Thunno 2, 4 bytes
Þḃ1c

Attempt This Online!
Alternatively:
Þ2BS

Attempt This Online!
Explanation
Þḃ1c  # Implicit input
Þ     # Sort the input by the following:
 ḃ    #  Convert the number to binary
  1c  #  Count the number of 1s
      # Implicit output

Þ2BS  # Implicit input
Þ     # Sort the input by the following:
 2B   #  Convert the number to a binary list
   S  #  Sum the resulting list
      # Implicit output

Jelly, 5 bytes
BS$ÞṚ

Try it online!

PHP, 71
usort($a,function($a,$b){for(;$a&&$b;$a&=$a-1,$b&=$b-1);return$b-$a;});

If we assume there will be no dulicates, 69
foreach($a as$v)$b[$v]=gmp_popcount($v);arsort($b);$a=array_keys($b);

If we accept ascending sort, 68
foreach($a as$v)$b[$v]=gmp_popcount($v);asort($b);$a=array_keys($b);

That is, given $a. So, I'm unclear on whether we can assume the input, as various solutions go to various lengths to get it.

Actually, you´d habe to use $argv and print_r the result or add the 23 bytes function overhead: function($a){return$a;}. gmp is not in the default config and actually you´d had to add the bytecount of installation or at least the necessary config line. Nice ones nonetheless.

Perl 5, 51 bytes
sub j{(sprintf'%b',@_)=~y/1//}say sort{j($b)-j$a}<>

Try it online!

Pyth, 8 6 bytes
_osjN2

Try it online!
Explanation
_osjN2  | Full code
_osjN2Q | with implicit variables
--------+------------------------
 o    Q | Sort the input by
   jN2  |  convert to binary list
  s     |  sum
_       | Reverse

Python 2, 59 bytes
def f(l):l.sort(key=lambda x:`bin(x)`.count('1'),reverse=1)

Try it online!

Save 7 bytes by replacing reverse=1 with *-1 to get descending order.  Try it online!

Pyt, 19 bytes
ĐĐ↑Ḷ⌊⁺ᴇĐ3ȘĦ*⇹↔+Ş⇹%Ɩ

Try it online!
Explanation
                         Implicit input (as a list of integers)
ĐĐ                       Triplicate the list
  ↑                      Get the maximum value of the list (X_m)
   Ḷ⌊⁺ᴇĐ                 Push Y=10^(floor(log_10(X_m))+1) twice
        3Ș               Swap the top three elements on the list [puts the input on top]
          Ħ              Get the Hamming weight of each element of the input
           *             Multiply the Hamming weight by Y
            ⇹            Swap the top two elements on the stack
             ↔           Flip the stack [Puts the list on top, followed by Hamming weights multiplied by Y]
              +          Add the two lists element-wise [resulting in Z=[Z_0,Z_1,...]]
               Ş         Sort the resulting list in descending order
                ⇹        Swap the top two elements on the stack
                 %       Take Z mod Y
                  Ɩ      Convert Z mod Y to integers
                         Implicit print

This is as long as it is because Pyt doesn't allow sorting by anything other than the values in the array; this means that a workaround had to be devised to allow the proper sorting

K (oK), 19 bytes
{t@>+/'(99#2)\'t:x}

Try it online!

Dart, 102 99 84 bytes
F(a)=>'1'.allMatches(a.toRadixString(2)).length;f(List l)=>l.sort((a,b)=>F(a)-F(b));

Try it online!
-3 bytes by using allMatches instead of replaceAll
-15 bytes by using - instead of compareTo and replacing List< int > by List

APL(NARS), 27 chars, 54 bytes
{⍵[⍒{+/(2⍴⍨⌊1+2⍟1+⍵)⊤⍵}¨⍵]}

test
  f←{⍵[⍒{+/(2⍴⍨⌊1+2⍟1+⍵)⊤⍵}¨⍵]}
  f 825 32425 15342 11746 28943 28436 21826 16375 15752 19944 3944
16375 15342 32425 11746 28943 28436 19944 15752 3944 825 21826

Perl 6, 36 bytes
@a.sort({sum .base(2).comb}).reverse

Try it online!

Taking input through a predefined variable is not allowed as it turns the submission into a snippet. Turning it into an anonymous code block is valid and the same length anyway

Some golfing tips: It's always shorter to use [R,] instead of reverse, though in this case, you can sprt be the negative of the sum instead. The sum can go on the end instead, like .sum and then you can turn it into an anonymous Whatever code object like -*.base(2).comb.sum. Of course, all this would make it a duplicate of nwellnhof's existing answer though don't let this discourage you! It's nice to see a new Perl 6 golfer!

J-uby, 33 bytes
:sort_by+(:%&"%b"|~:count&?1|:-@)

Attempt This Online!

Pyt, 16 bytes
ĐĦ⇹Đ↑⁺Đ3Ș⇹↔*+Ş⇹%

Try it online!
Pyt only allows for sorting on the values themselves, so a kludge had to be done.
Đ                     implicit input (v); Đuplicate
 Ħ                    get Ħamming weight of each element (H)
  ⇹Đ↑                 get maximum of input (m)
     ⁺                increment m
      Đ               Đuplicate m
       3Ș⇹↔           Stack manipulation
           *          multiply H by m+1
            +         Add v to H*(m+1)
             Ş        Şort in descending order
              ⇹%      modulo m+1; implicit print

Thunno, \$ 14 \log_{256}(96) \approx \$ 11.52 bytes
DebdiSEZZz;.AK

Attempt This Online!
Unfortunately Thunno lacks a "sort by" built-in.
Explanation
DebdiSEZZz;.AK  # Implicit input
De    E         # Duplicate and map:
  bd            #  Convert to binary
    iS          #  And sum the digits
       ZZ       # Zip with input
         z;     # Reverse-sort
           .AK  # Last element of each
                # Implicit output


text:
Letters in phone numbers
Problem:
You are making a new phone where people can type in specialized phone numbers, for example, 1-800-program, and they would be converted automatically to a usable phone number, like 1-800-7764726 (for the previous example).
Your program will recieve a string if any length with numbers, letters and dashes, and convert all the letters to their corresponding numbers.
Here is a keypad, for reference:

Rules:

Your program will receive a string
It will process it and return/print another string
Any language is accepted
Since it is code-golf, the shortest code wins

Should the program handle both upper and lower case letters in the input?

@mattnewport - no, assume the variable has been turned into lowercase already

GolfScript, 24 chars
{.96>{,91,'qx'+-,3/`}*}%

Test input:
0123456789-abcdefghijklmnopqrstuvwxyz

Test output:
0123456789-22233344455566677778889999

Explanation:

{ }% applies the code between the braces to each character of the input.
.96>{ }* executes the code between the inner braces if and only if the ASCII code of the character is greater than 96 (i.e. it is a lowercase letter).
The first , turns the character into a list of all characters with lower ASCII codes, and 91,'qx'+- filters out all characters with ASCII codes less than 91, as well as the letters q and x, from the list.
Thus, for example, the character a gets turned into the 6-character list [\]^_`, while z gets turned into the 29-character list [\]^_`abcdefghijklmnoprstuvwy.
The second , counts the elements remaining in the list, and 3/ divides this count by three (rounding down).  Finally, the ` turns the resulting number (in the range 2 – 9) into a string.

Thus, as per spec, hyphens and numbers are left unchanged, while lowercase letters are mapped into numbers according to the reference keypad diagram.  The code will actually cleanly pass through all printable ASCII characters except for lowercase letters (which as mapped as described) and the characters {, | and } (which are mapped to the two-character string 10).  Non-ASCII 8-bit input will produce all sorts of weird numeric output.
After all this, it's a bit disappointing that this only beats the trivial bash solution by just six chars.

Bash, 30
Edit: Thank you Doorknob for eliminating 3 chars
tr a-z 22233344455566677778889

Example:

Can't you remove the last 3 9s?

C, 83 78 77 65 63 62
main(c){for(;~(c=getchar());putchar(c>96?20-c/122+5*c/16:c));}

http://ideone.com/qMsIFQ

Nice math. Just wanna say that you can reduce 1 char by assuming EOF is -1 and do ~(c=getchar())

Couldn't you use getch() instead of getchar()?

Strictly speaking, getch() isn't standard C, as a result I guess it doesn't link in ideone. I tested it in MSVC anyway though and it doesn't really work sadly - as it directly consumes keyboard input there's no way to exit the program, although it does translate what you type on the fly which is kind of neat.

Javascript - 103 characters
alert(prompt().replace(/[a-z]/g,function(y){y=y.charCodeAt(0)-91;return y>27?9:y>24?8:y>20?7:~~(y/3)}))

I didn't know you could do that with .replace. Up vote for you!

You can replace charCodeAt(0) with charCodeAt() and you can use arrow function for function(y)... to save few bytes and for ~~(y/3) you can use y/3|0

Ruby, 75 chars
gets.chars{|c|$><<"22233344455566677778889999#{c}"[[*?a..?z].index(c)||-1]}

Uses the deprecated chars with block, and prints each letter individually with $><<. I also like [[*?a..?z].index(c)||-1]; it grabs the character corresponding to that letter of the alphabet if it's a letter, and the last character (which happens to be the test character unchanged) if not.
Ruby, 43 (or 35) chars
Blatantly stealing from @ace ;)
puts gets.tr'a-z','22233344455566677778889'

Shave off 8 chars if I can run in IRB with the variable s as the string:
s.tr'a-z','22233344455566677778889'

C++ - 222 chars
Longest solution so far:
#include<iostream>
#include<string>
#define o std::cout<<
int main(){std::string s;std::cin>>s;for(int i=0;i<s.size();i++){int j=s[i]-97;if(j<0)o s[i];if(0<=j&j<15)o 2+j/3;if(14<j&j<19)o 7;if(18<j&j<22)o 8;if(21<j&j<26)o 9;}}

Lol, I don't think longest solution is the goal here...

@Danny C++ does not lend itself well to [tag:code-golf].  Java and C# are the only languages that are worse, that I know of (all the classes, object creation, and long names for output...).

I know, I just thought it was funny that you mentioned "Longest solution".

Frink, 92
A rather verbose language, I know. This checks 8 values instead of 26 without having to type out the compares. Can any of the above "222333444.." solutions be reduced in a similar way?
Using built in structures, 107
co=new OrderedList
co.insertAll[charList["cfilosv{"]]
println[input[""]=~%s/([a-z])/co.binarySearch[$1]+2/eg]

Using a custom recursive function, 92
fn[x,a]:=x<=(charList["cfilosv{"])@a?a+2:fn[x,a+1]
println[input[""]=~%s/([a-z])/fn[$1,0]/eg]

+1 for reducing the string-translation method to an 8-character search. Nice touch.

Python 2.7, 66 65

Anakata's Original
for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c),

Further golfed
for c in input():print(ord(c)-91)/3-(c in('svyz'))if c>'`'else c,

I don't have enough reputation to comment on @anakata's answer, so I made a separate post here. I had the same idea (taking the ordinance modulus 3) but couldn't figure out how to print the right numbers for s - z.
Anyways, the golf improvements I made:

changed raw_input to input
removed the extraneous '\b' and parentheses and single quotes
removed the +2 offset and placed that in the original subtraction (97 - (3 * 2) = 91)

Tested with the Python 2.7.6 interpreter. Assumes, per the rules, a string input.

you could also remove the space between the ) and the if

You're right. good catch willem

Scala, 49 48 bytes
_.map(c=>if(c>96)(c/3.2+20).toChar min'9'else c)

Try it online!
Maps abcdefghijklmnopqrstuvwxyz to 22233344455566677778889999 via (c/3.2+20).toChar min'9'
(saved 1 byte thanks to Kevin Cruijssen)

You can remove the space at min'9' for -1.

Smalltalk, 79 70
input is s:
s collect:[:c|' 22233344455566677778889999'at:1put:c;at:(($ato:$z)indexOf:c)+1]

probably not a candidate for being shortest - but may be of interest for an old trick to avoid a test for a not-found condition (indexOf: returns 0 in this case).  So no special test for letters is needed. Some Smalltalks however, have immutable strings, and we need 4 more chars ("copy").
Oh, a better version, which even deals with immutable strings in 70 chars:
s collect:[:c|c,'22233344455566677778889999'at:(($ato:$z)indexOf:c)+1]

Mathematica 90
This follows the logic of @ace's solution:
StringReplace[#,Thread[CharacterRange["A","Z"]->Characters@"22233344455566677778889999"]]&

Example
StringReplace[#1,Thread[CharacterRange["A","Z"]->
Characters@"22233344455566677778889999"]]&["VI37889"]

8437889

Your arrow character representation isn't accepted by Mma in a copy/paste

Also,you don't need the 1 in #1:)

Belisarius, I changed the arrow back and removed the 1.  Still 90 char but cut and paste will work. You understand of course the motivation to use the single char arrow.

Been there, done that :)

Perl, 50
Another obvious copy of Ace's bash answer
($_)=@ARGV;y/a-z/22233344455566677778889999/;print

This code is working correctly but there's room for improvement. Let's get rid of $ARGV[0] and use -p switch instead which lets you nicely go through each line of stdin.  While we're at it, the range in y/// doesn't need to be put in square brackets. We can also get rid of three 9's leaving just one and remove the final semi-colon:
`-p y/a-z/22233344455566677778889/`

There you go, 30 + 1 for -p. Thank you for using Enterprise Chinese Perl Golfing and Optimization Services and have a nice day.

PHP, 141
Not the shortest, but more fun:
<?php foreach(str_split($argv[1])as$c){$v=ord($c);if($v>114){$v--;}if($v==121){$v--;}if($v<123&$v>96){echo chr(ceil($v/3+17));}else{echo$c;}}

More readable:
<?php
foreach (str_split($argv[1]) as $c) {
  $v=ord($c);
  if ($v>114) {$v--;}
  if ($v==121){$v--;}
  if ($v<123 & $v>96){
    echo chr(ceil($v/3+17));
    } else {echo $c;}
}

OP said that the input is already in lowercase, so you can remove the strtolower

R, very long but fun
foo <- '1-800-splurghazquieaobuer57'
oof <- unlist(strsplit(foo,''))
#don't count that part - it's input formatting :-)
digout <- unlist(strsplit('22233344455566677778889999',''))
oof[oof%in%letters[1:26]] <- unlist(sapply(oof[oof%in%letters[1:26]], function(j) digout[which(letters[1:26]==j)] ))

k [32 Chars]
{(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}

Usage
{(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}"stack exchange"
"78225 39242643"

JavaScript, 85
JavaScript is never going to win the golf wars, but I like it and I wanted to do something different than jump on the @ace bandwagon.
alert(prompt().replace(/[a-z]/g,function(a){for(i=7;a<"dgjmptw{"[i--];);return i+4}))

T-SQL, 216 bytes
I spent quite some time over the past couple of nights painstakingly creating a mathematical sequence function that would round correctly to generate the proper ASCII codes for the numbers from the alphabetical ASCII codes. It had a ridiculous number of decimal places in the coefficients, but it worked.
However, mattnewport's rational approach works in SQL as well, at a much lower cost of bytes, so I am shamelessly scrapping my own math in favor of his. Go up-vote him, it's an elegant solution!
Here's mine:
DECLARE @p VARCHAR(MAX)='';WITH t AS(SELECT ASCII(LEFT(@s,1))c,2 i UNION ALL SELECT ASCII(SUBSTRING(@s,i,1)),i+1FROM t WHERE i<=LEN(@s))SELECT @p=@p+CHAR(CASE WHEN c>96THEN 20-c/122+5*c/16 ELSE c END)FROM t;SELECT @p

This uses a recursive CTE to make an impromptu stack of the characters in the phone number and translate the letters on the fly, then a bit of SQL trickery (SELECT @p=@p+columnValue) to recompose the string from the CTE without requiring another recursion construct.
Output:
DECLARE @s VARCHAR(MAX)='1-800-abcdefghijklmnopqrstuvwxyz'
--above code runs here
1-800-22233344455566677778889999

Python 2.7, 80
for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c),

I am new to python, so I'm sure there must be a way to golf this even further, it's a different aproach, hope you guys like it, my god, is python pretty!
Run example:

input:  01-800-abcdefghijklmnopqrstuvwxyz
output: 01-800-22233344455566677778889999

05AB1E, 11 bytes
Aā6+žq÷T9:‡

Try it online!
A                 # alphabet: "abcdefghijklmnoqrstuvwxyz"
 ā                # length range: [1..26]
  6+              # add 6 to each: [7..32]
    žq÷           # divide by pi: [2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10]
       T9:        # replace 10 with 9
          ‡       # transliterate the input (a => 2, ..., z => 9)

Vyxal, 14 bytes
ka:ż6+kiḭṪ9JṅĿ

Try it Online!
ka:ż6+kiḭṪ9JṅĿ
ka:            # Push the alphabet twice
   ż           # Length range: [1..26]
    6+         # Add 6: [7..32]
      kiḭ      # Floor divide by pi: [2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10]
         Ṫ9J   # Remove the last item and append 10
            ṅ  # Join by nothing to make a string
             Ŀ # Transliterate the input from the alphabet to this

PHP, 87
echo str_ireplace(range('a','z'),str_split('22233344455566677778889999'),fgets(STDIN));

q [38 Chars]
{(.Q.a!"22233344455566677778889999")x}

Inspired by @ace's solution
Example
{(.Q.a!"22233344455566677778889999")x}"stack exchange"
"78225 39242643"

C# 140
using System.Linq;class P{static void Main(string[]a){System.Console.Write(string.Concat(a[0].Select(d=>(char)(d>96?20-d/122+5*d/16:d))));}}

XQuery, 71
BaseX was used as XQuery processor. $i is input.
translate($i,"abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")

Not the shortest answer, but quite short and very readable.

Python, very ungolfed
Since everyone is copying ace, i decided to post the code i made up before i submitted the question:
def phonekeypad(text):
    c = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
    st = ""
    for i in list(text):
        a = False
        for t in range(len(c)):
            if i in c[t]:
                st += str(t)
                a=True
        if a == False:
            st += str(i)
    return st

EcmaScript 6 (103 bytes):
i.replace(/[a-z]/g,x=>keys(a='00abc0def0ghi0jkl0mno0pqrs0tuv0wxyz'.split(0)).find(X=>a[X].contains(x)))

Expects i to contain the string.
Try it in any recent version of Firefox. I've not tried Google Chrome.

You can replace split(0) with split\0``

@LeoDog896 True, but that doesn't save any bytes.

Python 3, 121
print("".join((lambda x:"22233344455566677778889999"[ord(x)-97] if ord(x)>96 and ord(x)<123 else x)(i) for i in input()))

Haskell, 93C
t[]_ a=a
t(b:c)(d:e)a
 |a==b=d
 |True=t c e a
y=map(t['a'..'z']"22233344455566677778889999")

Usage
y "1-800-program"

Perl, 54
print map{/[a-y]/?int(5/16*ord)-28:/z/?9:$_}<>=~/./gs

Shoot, @RobHoare still beat me by 4 characters. :)

C++ (clang), 50 bytes
[](auto&s){for(auto&c:s)c=c>96?20-c/122+5*c/16:c;}

this is a port of mattnewport's C solution.
Try it online!

QBasic, 155
Ah, the memories...
INPUT n$
FOR i=1 TO LEN(n$)
c$=MID$(n$,i,1)
a=ASC(c$)
IF 97>a THEN
PRINT c$;
ELSE IF 122>a THEN
PRINT STR$(a\3.2-28);
ELSE
PRINT 9;
END IF
NEXT i

This should have been shorter, but I was testing with repl.it, which doesn't allow single-line IF statements and behaves strangely if you leave the variable off of NEXT i.  It also doesn't recognize the ASC function, so to run the code you'll need to add this workaround at the beginning:
DECLARE FUNCTION ASC(s$)
FUNCTION ASC(s$)
FOR j=1 TO 255
IF CHR$(j)=LEFT$(s$,1) THEN
ASC=j
END IF
NEXT j
END FUNCTION

(The second time you run it, the interpreter will complain unless you remove the DECLARE FUNCTION line, go figure.)

R, 110
s=strsplit(scan(,""),"")[[1]];i=grep("[a-z]",s);s[i]=sort(c(1:24%%8+2,7,9))[match(s[i],letters)];cat(s,sep="")

Example:
> s=strsplit(scan(,""),"")[[1]];i=grep("[a-z]",s);s[i]=sort(c(1:24%%8+2,7,9))[match(s[i],letters)];cat(s,sep="")
1: 1-800-program
2:
Read 1 item
1-800-7764726

Python
import string
trans = str.maketrans(string.ascii_lowercase,
                      '22233344455566677778889999')
print("1-800-ask-usps".translate(trans))

ECMASCRIPT, 101 (with input)
"1-800-PROGRAM".replace(/./g,function(c){
return "22233344455566677778889999"[c.charCodeAt(0)-65]||c})

Newline added for clarity.  85 characters if the input is in a variable.

VB.net (61c)
Excludes the 45c min for a valid vb.net program.
Module P
Sub Main(A()As string)
For Each x In A(0).ToUpper
Console.Write(If(x<"A"or x>"Z",x,Chr(Asc(x)\4+35)))
Next
End Sub
End Module

brainfuck, 326 bytes
,[>+[-[---<]>>-]<--<<<[>>>>+<[->[-]>+<<]>[-<<+>>]>[-<<+>>]<<-<<+<-]+>>[<<->[-]>->[<+>+]<->>+++++[>+++++<-]>[<+>-]+<<<[>>-<+<-]>[<+>-]>[>-<[-]]>[<<<->>>-]++++[>++++<-]>+<<<<[>>+>>[-<<[-]>+>]<<[-<+>]>[->+<]>-<<<<<+>-]>>>>[-]<<<[<<->>-]<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]+++++[>++++++++++<-]>.[-]<<]<<[->.>>[-]<<<]>[-]<,]

Try it online!
For each character:

Check if it's a letter. If not, print it and go to the next character.
Check if it's 'z'. If it is, subtract 1 to make it 'y'
Check if it's after 'r'. If it is, subtract 1 to realign it with the number grid.
Divide the letter number by 3.
Add the result to 50 ('2') and print it.

stage0 memory layout:
| input x | input backup | compare result z | compare val y | compare t0 | compare t1 |
stage1:
| else flag | input backup | prev compare result / letter index y | inv letter index / compare t0 | compare t1 | compare val x |
stage2:
| else flag | letter index backup | letter index x | compare result z | compare t0 | compare t1 | compare val y |

,[ Read first character
    >+[-[---<]>>-]<-- Check if input is greater than 96 (a lowercase letter)
    <<<[>>>>+
        <[->[-]>+<<]
        >[-<<+>>]
        >[-<<+>>]
        <<-<<+<-
    ]

    + Set else flag
    >>[ If input is a letter:
        ((stage1))
        <<->[-]>- Clear the result/else flags
        >[<+>+]<- Invert the letter index

        >>+++++[>+++++<-]> Check if letter 25 (z)
        [<+>-]+
        <<<[>>-<+<-]
        >[<+>-]
        >[>-<[-]]
        >[<<<->>>-] If it is subtract 1 to change it to y

        ((stage2))
        ++++[>++++<-]>+ Check if greater than letter 17 (r)
        <<<<[>>+
            >>[-<<[-]>+>]
            <<[-<+>]
            >[->+<]
            >-<<<<<+>-
        ]
        >>>>[-] Clear y
        <<<[<<->>-] If it is subtract 1 to normalize indices
        <+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<] Divide normalized index by 3
        >[-]>[-] Clear tempvars from division
        +++++[>++++++++++<-]>. Add 50 ('2') to result and print it
        [-]<< Clear letter index

        ((stage0))
    ]<<[ If input isn't a letter:
        - Clear the result flag
        >. Just print the character
        >>[-]<<< Clear the letter index
    ]
    >[-]<, Next input
]

Retina, 27 bytes
T`l`22233344455566677778889

Try it online!
Port of the Bash solution. Transliterates each lowercase letter to a digit between 2 and 9. The list is implicitly padded with 3 additional 9s

Haskell, 80 bytes
d c|elem c['a'..'z']="22233344455566677778889999"!!(fromEnum c-97)|1>0=c
l=map d

Try it online!

Rust, 196 bytes
x.iter().map(|x|match x{'a'|'b'|'c'=>'2','d'|'e'|'f'=>'3','g'|'h'|'i'=>'4','j'|'k'|'l'=>'5','m'|'n'|'o'=>'6','p'|'q'|'r'|'s'=>'7','t'|'u'|'v'=>'8','w'|'x'|'y'|'z'=>'9',_=>*x}).collect::<Vec<_>>();

Try it online!
Power of match. Yet match for every letter feels unnecessarily tedious. Still trying to grasp iter() and subsequent functions

Thunno 2, 11 bytes
Ạż6+kP÷T9vṆ

Try it online!
Explanation
Ạż6+kP÷T9vṆ  # Implicit input
Ạ            # Push the lowercase alphabet
 ż           # Without popping, push [1..26]
  6+         # Add 6 to make it [7..26]
    kP÷      # Floor divide each by pi
       T9v   # Replace the 10 with a 9
          Ṇ  # Transliterate the input
             # Implicit output

Python 3, 130 bytes
d=lambda x:str(int((ord(x)-96)*.31769+1.76715))
def f(s,c=''):
	for i in s:c+=(d(i)if i!='z'else'9')if i.isalpha()else i
	print(c)

Try it online!
Uses the formula y = (x * .31769) + 1.76715 to approximate the given relation. Sadly this formula gives wring value for z hence requires one additional check

80

65 based on the above

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Print E=mc² or E=mc^2, by using the right side of this equation
Your task – if you choose to accept it – is to have your program print, literally, either one of the following:

E=mc² (if your language supports Unicode (so no HTML trickery, for instance))
E=mc^2 (if your language doesn't support Unicode)

Here are the conditions:

Your program must consist of exactly two expressions (one representing the m, the other the c, in mc²), which, when fed into your language's representation of the formula mc², and whose result is then printed, will show one of the above results.
Both expression may be assigned to variables before feeding them into mc², but the expressions themselves are not allowed to use intermediate variables.
Both expressions must evaluate to an absolute value larger than 1 (e.g abs(expression) > 1).
You may assign the result of mc² to an intermediate variable, representing the E, before printing this E, but that is not necessary – you may print the result of mc² directly as well.
When printing the final result, you are allowed to use your language's libraries to convert the possibly numeric or binary result to it's string representation.
Added condition: no operator overloading in the final expression that represents mc². The result must be the algebraic result of expression m times expression c squared.

Here's an example template, of what I'm looking for, expressed in PHP:
$m = /* some expression */;
$c = /* some expression */;
$E = $m * pow( $c, 2 );
print $E; // should print on of the results mentioned at the beginning of this challenge

To be honest, I'm not even sure this challenge is doable, but my gut says it must be possible in at least one, or even a few, languages.
Winning solution is the one with the shortest code, in characters, in a week from now.
For clarification, it's perfectly fine to merely do something like this as well — if your language allows for it:
print( someExpression * someOtherExpression ** 2 ); // or something to that effect

... in other words: without assigning anything to any intermediate variables. Just as long as the algebraic calculation remains intact.

This seems like it would be extremely easy to do with operator overloading

@Hannesh Hmm, yeah, I think I'll disallow operator overloading; at least in the final expression representing mc² (if it's even at all possible to be that selective with operator overloading).

Any restrictions in the usage of trailing whitespaces or zero-space unicode characters?

@ThomasW. Yes: no (trailing) whitespace and/or zero-space unicode chars in the output (unless, for instance, a trailing newline is absolutely required by your language).

Point of clarification. Your example assigns the expressions to variables as do many of the solutions, but bullet point 2 says "Both expression may be assigned to variables". Does that mean we can just do E=m-expressionc-expression^2 without any other variable assignments? I can save a fair number of bytes if so. e.g. E=38631826306^2 ?

@JonathanVanMatre Yes, you are allowed to do that.

@JonathanVanMatre You are even allowed to do print(3*8631826306^2), or something similar (without assigning to an intermediate E variable), if that works. Just as long as both "m" and "c" expressions evaluate to an absolute value larger than 1.

Haha, the joke is that in T-SQL ^ is a bitwise XOR. To do an exponent you have to do POWER(root, exponent). But one of these days I am going to do a crazy bit-math solution in SQL, just for fun.

@JonathanVanMatre Yeah, that's unfortunate; pretty much the same with PHP.

APL, 27
⎕UCS(2÷⍨⎕UCS'E=mc²')×(√2)*2

Ungolfed:
m←(⎕UCS 'E=mc²')÷2
c←√2
⎕UCS m×c*2

Start with the desired output string, convert it into an array of Unicode values, divide each number by 2, and assign the vector to m. Then assign √2 to c. Compute the formula and convert the resulting array back to a string. I can't tell whether the last operation is allowed by the rules, but it's akin to what most other solutions are doing, whether explicitly or implicitly.

The ungolfed version does not seems to be less golfed than the golfed one to me.

@Victor it gives names to things (m, c) and it doesn't cram everything in a single line. Other than that, no, there's not much to ungolf here.

C, 66 59 57 bytes
Ignore the compiler warnings. It should work OK as long as you compile it on a big little-endian machine. This code could probably be made a lot shorter on a 64-bit machine, but I'm unable to test:
main(){long long m=1130224008533LL,c=7,E=m*c*c;puts(&E);}

9 fewer characters thanks to @Adam Davis and @Michael :-)

This even works on Ideone: http://ideone.com/SCqKFm

So far, your solution meets the requirements most strictly. As far as I can tell it ticks all the boxes.

You can save some space by using 0x1072699BD55 in place of 1130224008533LL.

Also you can probably use puts( to replace printf("%s",

@AdamDavis Ah, I always forget about puts(). Thanks for pointing that out. Writing the number in hex doesn't help unfortunately — the 0x and LL are both required.

@AdamDavis No, it's definitely null terminated. E=mc^2 is only 6 characters, so it's followed by two zero bytes.

Ah, right!  I'm reading the string backwards, of course.

Why is the LL required? long long m=1130224008533LL and long long m=1130224008533 are supposed to set m to the exact same value, and on my system, that does indeed work.

On 64 bit, you can use long instead of long long.

On big-endian, I think m=76130130550322LL,c=256 or m=2165479268986938LL,c=48 work. (I prefer the 2nd one)

Also, why don't you assign the value directly in E ? long long m=1130224008533LL,c=7,E=m*c*c;

Are you not allowed to do this directly: puts(m*c*c);, without using the intermediate E variable? Or perhaps even something like puts((long long m=1130224008533LL)*7*7)? (Forgive me my ignorance of C — just spitballing)

@Michael Of course! Thanks for that. @fireeyedboy Can't do that because puts() needs a pointer as its argument, not an integer.

C, 57 53 50 40 39 bytes
The rules are somewhat confusing, I do hope I read them correctly.
Works on 32bit platforms only.
m="E=mc^2",c=-1u/2;
main(){
    puts(m*c*c);
}

cc equals 2^31-1, so c*c equals 1 modulo 2^32. Therefore m*c*c == m (mod 2^32).
The -1u/2 constant and puts are hvd's suggestions.

Sorry, but the rules stated that the expressions may not evaluate to 1 (c=1 here).

Thanks @fireeyedboy, fixed. And shortened while I'm at it.

Is the intermediate variable s necessary? (Or is that a constant perhaps?) Would something like m="E=mc^2"/4; not be possible, for instance? (Sorry, not a C programmer.)

I get "error: initializer element is not computable at load time" with GCC 4.8.

@fireeyedboy That wouldn't work, compilers are lenient with implicit conversions between pointers and integers, but not lenient enough to allow division with a pointer operand.

Modified to 49 bytes and to compile on my system: m="E=mc^2",c=-1u/2;main(){printf("%s\n",m*c*c);} (Comment edited, it was 52 bytes.)

Addition to my previous comment: using puts instead of printf trims it to 40 bytes.

Thanks @hvd. Can't believe I missed puts.

Oops, I miscounted, sorry! Making c global does save a character, so what I had was actually 39 bytes, not 40: I accidentally counted one more because I included an unnecessary newline character.

@hvd I see. Thank you for clearing that up.

Java: 261 241 207 206 characters
Thanks to @V-X for helping me with ideas for optimizing this.
Here it is, 206 characters:
import java.math.*;class N{public static void main(String[]y){BigInteger m=new BigInteger("12uy4kc5e",36),c=new BigInteger("5"),e=m.multiply(c).multiply(c);System.out.println(new String(e.toByteArray()));}}

Properly indented version:
import java.math.*;
class N {
    public static void main(String[] y) {
        BigInteger m = new BigInteger("12uy4kc5e",36),
                   c = new BigInteger("5"),
                   e = m.multiply(c).multiply(c); // e = m * c * c
        System.out.println(new String(e.toByteArray()));
    }
}

Older version, Java 8 only, with 261 characters:
import java.math.*;public class N{public static void main(String[]y){BigDecimal m=new BigDecimal("59324209849366147.77"),c=BigDecimal.TEN,e=m.multiply(c).multiply(c);System.out.println(new String(java.util.Base64.getDecoder().decode(e.toBigInteger().toByteArray())));}}

Ungolfed version:
import java.math.*;
import static java.util.Base64.*;

public class N {
    public static void main(String[] y) {
        BigDecimal m = new BigDecimal("59324209849366147.77"),
                   c = BigDecimal.TEN,
                   e = m.multiply(c).multiply(c); // e = m * c * c

        System.out.println(new String(getDecoder().decode(e.toBigInteger().toByteArray())));
    }
}

Java ftw! I really enjoy all your Java answers.

Could reduce 4 bytes if I do not use an intermediate variable for e. But I prefer to use the intermediate var anyway.

by use of m=new BigDecimal("1130224008533"),c=new BigDecimal(7), you can get rid of 4 more characters...

@V-X I tried your suggestion and the program failed with java.lang.IllegalArgumentException: Illegal base64 character 5e.

Does Java support import aliases? For instance import java.math.BigDecimal as B? Might help with shaving off a few extra chars.

@fireeyedboy No, java does not have this feature.

I have tried this import java.math.*; public class N {    public static void main(String a[])    {       BigInteger m = new BigInteger("1130224008533"),                  c = new BigInteger("7"),                  e = m.multiply(c).multiply(c);                          System.out.println(new String(e.toByteArray()));    } } (215 chars after removing irrelevant spaces) but it was printing in the reversed order (I tried that in javalunch.com)

@V-X Initially I wanted to use BigIntegers, but unfortunately 5932420984936614777 is a squarefree number. And since java supports Unicode, it must print E=mc² instead of E=mc^2. Further, the code to reverse the String in your idea got too complex to be usable. But, your comment inspired me for trying to encode it differently, and I figured out that I could use a different charset, and voila: Quickly got a new shorter version by using ISO-8859-1.

Is there a reason for the specification of the charset?

@V-X This is just to make the bytes encoding E=mc² to form a BigInteger which the value has at least one squared factor, i.e, something very hackish. If I do not specify the charset, it outputs E=mc�.

@V-X You are right. By switching to UTF-8 encoded, I do not need to specify the encoding anymore.

I have another idea: you can transform BigInteger m = new BigInteger("3045205223042"); into BigInteger m = new BigInteger("12uy4kc5e",36); which is by 1 character shorter:)

Perl - 32 characters
$m="E=mc²";$c=1.1;print$m x$c**2

This is sort of cheating: in Perl's x operator, the right operand is converted to an integer, so both 1.1 and 1.21 (1.1**2), despite having a value larger than 1, behave exactly as 1.

Haha, sneaky. ;-)

TI-89 basic (needs CAS) - 17
solve(√(e/m)=c,e)

Edited - it now works (according to my calculator):
e = c^2 * m and c >= 0

Looks neat, but would you mind explaining how this arrives at one of the requested solutions?

CAS = Computer Algebra System. It will solve the given equation (sqrt(em)=c) for e to give the incorrect equation e=c^2/m.

@KyleKanos gotcha, thanks. TheDoctor: back to the drawing board, I guess. ;-) Close though.

@fireeyedboy - oops...

Not seeing how does it comply with the rules, there aren't 2 expressions, for m and for c

Smalltalk, 110 58 56
Version 2 below does it, but I guess version1 is interesting enough to not cut it. Read for your amusement (it's about fun here - isn't it)
Version 1:
code:
(Class name:#S subclassOf:String)compile:'*t^''E='',self,t';compile:'squared^self,''²'''.m:='m'as:S.c:='c'as:S

evaluate:
m*c squared

result:
   'E=mc²'
I really have a hard time to understand what you expect :-(, so I'll give some more detail than usual. Maybe it is of interest to others, even if it does not golf.
First, you want the standard language syntax to be used, eg. in Smalltalk, I would write:
m := 100.
c := 299792500.
E := m * c squared.

to get "8987554305625000000".
So you want this to be done symbolically. In ST we need a class which redefines the above used operators into string concatenations (any class would do, but I'll inherit from String for convenience, so I get the ,-operator):
Class name:#MyString subclassOf:String

    * thingy
        ^ self,thingy asString

    squared
        ^ self,'²'

    = thingy
        ^ self,'=',thingy

So now, I can write:
m := MyString fromString:'m'.  "/ or 'm' as:MyString for short
c := MyString fromString:'c'.
(m * c squared) print

and get 'mc²' as output.
However, and that's my problem: the assignment cannot be redefined,
so saying:
E := (m * c squared).
E print

would print the same.
In Smalltalk, "=" is a comparison operator (not assignment). "=" was already redefined in the above code. However, as I am calling for a comparison of E against the right side, I need to preset E to something non-nil first:
E := MyString fromString:'E'.

So let's write:
(E = m * c squared) print

gives us (the requested?): 'E=mc²'
As you wanted the result of m*c squared, I'll push the 'E' into the multiplication operator:
* thingy
    ^ 'E=',self,thingy

to fullfill your requirements.
PS: the second comment made it obvious; all I have to change is the assignment in the above class to generate the 'E'.
Version 2:
Obviously I was thinking way too complicated:
m:=36rEF7U6YC5.c:=7.E:=m*c squared.E digitBytes asString

also outputs: 'E=mc^2'
Edit: The large number 1130224008533 is obviously shorter if written in a higher base - hex for example; but it is much shorter in base 36, which in Smalltalk is written as 36rEF7U6YC5. This saves me another 2 characters.
PS: how to get to the magic numbers:
LargeInteger digitBytes:'E=mc^2' asByteArray-> 55380976418117
55380976418117 primeFactors-> Bag('4728970747(*1)' '7(*2)' '239(*1)')

So where's the answer? You need to provide a program, and say how long it is. Then you can explain how and why.

Basically what I'm looking for is: have two expressions m and c, for which the result of m times c squared, when printed as a string, will yield E=mc². Have a look at squeamish ossifrage's solution in C, for an example.

that made it clear; I hope I got it right now.

Sorry, I know next to nothing about Smalltalk to evaluate whether your first solution was too complicated, although I had a strong feeling it was. But your second solution seems to confirm that indeed it was. ;-) That looks a lot more like what I expected to find and what others have come up with as well. Nice one!

Lua - 74
c=rawset(_G,"print",function()io.write"E=mc^2\n"end)and 2 m=2 print(m*c^2)

A little cheaty, but not prohibited by the rules:

Exactly 2 expressions, one for c, another for m.
No intermediate variables
No operator overloading

T-SQL - 86 bytes 75 bytes
I'm pretty proud of how competitive this one is for SQL the verbose blabbermouth.
Found myself wishing SQL had a 64-bit binary data type so I could possibly find a bigger square root than 3, but this comes out as a pretty lean one-liner anyway. And it prints the pretty Unicode version! (Which is good, because there were no squares to factor out of the number for E=mc^2)
And it smokes the Java entry. ;-)
Jus' kiddin' - @Victor and I are kindred spirits, more interested in playing our best game than winning the prize. Here's to we the crazy ones!
New Hotness, 75 bytes
I was hoping for a larger improvement, but due to the vagaries of the query processor I have to explicitly declare @m as a BIGINT or SQL chooses the wrong bit size and the binary result is wrong.  Still, better is better.
DECLARE @m BIGINT=33042591394;SELECT CAST(CAST(@m*3*3 AS BINARY(5))AS CHAR)

Original Submission, 86 bytes
DECLARE @c INT=3,@m BIGINT=33042591394;SELECT CAST(CAST(@m*@c*@c AS BINARY(5))AS CHAR)

SQLFiddle Here.
Output:
E=mc²

I like it! Nice. :-)

C# 180 176 171 170 165
using System;namespace N{class P{static void Main(){var m=0x1072699BD55;var c=7;Console.Write(System.Text.Encoding.UTF8.GetString(BitConverter.GetBytes(m*c*c)));}}}

Concept like the Smalltalk version, just for C#.
Output: E=mc^2
Use the longer version var m=0x391DAF9277DEA5D; for E=mc² (actually followed by two spaces)
Edits:
180 to 176: remove 4 spaces
176 to 171: inline usings
171 to 170: Use UTF8 encoding
170 to 165: WriteLine->Write, outline using System; (thanks for the comments)

PauloHDSousa suggested that you add using System; at the beginning and change System.Console.WriteLine to Console.Write and System.BitConverter to BitConverter. His suggestion: using System;namespace N{class P{static void Main(){var m=1130224008533;var c=7;Console.Write(System.Text.Encoding.UTF8.GetString(BitConverter.GetBytes(m*c*c)));}}} I think that System.Text.Encoding could probably just become Text.Encoding (Seems logical). His suggestion saves 6 bytes, but if my idea works, you save 7+6=13 bytes

Unfortunately System.Text.Encoding cannot be shortened as proposed. BTW: how to count bytes reliably? Somehow my count differs by 1.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/