So you are given a base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number.

Examples:

1 => 1 (1 => 1)
2 => 1 (10 => 01)
3 => 3 (11 => 11)
4 => 1 (100 => 001)
5 => 5 (101 => 101)
6 => 3 (110 => 011)
7 => 7 (111 => 111)
8 => 1 (1000 => 0001)
9 => 9 (1001 => 1001)
10 => 5 (1010 => 0101)

This is a challenge, so the solution that uses the least bytes wins.

This challenge ends on January 12, 2017 at 0:00 UTC

share|improve this question
1  
Does "reverse the bits" mean reverse its binary digits? Sometimes it can also mean invert every bit. – ETHproductions 13 hours ago
    
Yes. Sorry for being unclear. – juniorRubyist 13 hours ago
    
This and this are veeeeery similar. – Geobits 13 hours ago
    
OEIS A030101. – orlp 13 hours ago
2  
Will the input always be positive? – Dennis 11 hours ago

26 Answers 26

Python, 29 bytes

lambda n:int(bin(n)[:1:-1],2)

Try it online

share|improve this answer
1  
This is what I would have done. ;) – juniorRubyist 13 hours ago

Python, 29 bytes

lambda n:int(bin(n)[:1:-1],2)

Try it online!

share|improve this answer
2  
Beat you by 9 seconds. – mbomb007 13 hours ago
    
@mbomb007 I beat you a few seconds too I guess, but I made a small mistake so I deleted mine xP – busukxuan 13 hours ago
2  
    
@mbomb007 They don't have to be deleted, according to meta – FlipTack 13 hours ago
3  
@mbomb007 so my answer is invalid because you clicked the post button 9 seconds before hand? Just because we reach the same golf at the same time doesn't mean we have to delete any answers. If anything, blame the 0-effort question. – FlipTack 13 hours ago

JavaScript (ES6), 30 bytes

f=(n,q=0)=>n?f(n>>1,q*2+n%2):q

This basically calculates the reverse one bit at a time: We start with q = 0; while n is positive, we multiply q by 2, sever the last bit off of n with n>>1, and add it to q with +n%2. When n reaches 0, the number has been successfully reversed, and we return q.

Thanks to JS's long built-in names, solving this challenge the easy way takes 44 bytes:

n=>+[...n.toString(2),'0b'].reverse().join``

Using recursion and a string, you can get an alternate 32 byte solution:

f=(n,q='0b')=>n?f(n>>1,q+n%2):+q
share|improve this answer
    
f=(n,q)=>n?f(n>>1,q*2|n%2):q almost works. But sadly not for n=0. – Arnauld 9 hours ago
    
@Arnauld OP has not yet replied as to whether the input will always be positive, but if so, then 0 doesn't have to be handled. – FlipTack 8 hours ago

J, 6 bytes

|.&.#:

|. reverse

&. under

#: base 2

share|improve this answer

Java 8, 53 47 46 bytes

-4 bytes thanks to Titus

This is a lambda expression which has the same principle as ETH's answer (although recursion would have been too verbose in Java, so we loop instead):

x->{int t=0;for(;x>0;x/=2)t=t*2+x%2;return t;}

Try it online!

Expanded, ungolfed and commented, it looks like this:

x -> { 
    int t = 0;           // Initialize result holder   
    while (x > 0) {      // While there are bits left in input:
        t <<= 1;         //   Add a 0 bit at the end of result
        t += x%2;        //   Set it to the last bit of x
        x >>= 1;         //   Hack off the last bit of x
    }              
    return t;            // Return the final result
};
share|improve this answer
    
Save 3 bytes with t*2 instead of (t<<1), one more with moving that calculation from loop head to loop body. Can You use x instead of x>0 for the condition? – Titus 9 hours ago
1  
@Titus not without an explicit cast to a boolean, but thanks for the other tips! Also just realised that x>>=1 can be replaced with x/=2 as it will automatically be integer division. – FlipTack 9 hours ago

05AB1E, 3 bytes

bRC

Try it online!

share|improve this answer

Jelly, 3 bytes

BUḄ

Try it online!

B   # convert to binary
 U  # reverse
  Ḅ # convert to decimal
share|improve this answer
1  
That's pretty short, BUB – Cyoce 9 hours ago

Japt, 5 bytes

¢w n2

Try it Online!

share|improve this answer
1  
Nice, exactly what I had. The ) could be a space too :-) – ETHproductions 13 hours ago

Bash/Unix utilities, 24 bytes

dc<<<2i`dc<<<2o$1p|rev`p

Try it online!

share|improve this answer

Ruby, 29 bytes

->n{("%b"%n).reverse.to_i(2)}
share|improve this answer
    
@Titus I think you misunderstand the answer. 2 is the base he is converting to, and n is the input. ->args{return value} is the ruby lambda syntax – Cyoce 9 hours ago

CJam, 8 bytes

ri2bW%2b

Try it online!

Explanation

ri          e# Read integer
  2b        e# Convert to binary array
    W%      e# Reverse array
      2b    e# Convert from binary array to number. Implicitly display
share|improve this answer

Perl 6, 19 bytes

{:2(.base(2).flip)}
share|improve this answer
    
Where is the input? – Titus 10 hours ago
    
This is a function that takes a single parameter $_. It isn't mentioned by name, but the base method is called on it. – Sean 9 hours ago

Mathematica, 19 bytes

#~IntegerReverse~2&
share|improve this answer

Java 8, 84 79 73 72 bytes

a->a.valueOf(new StringBuffer(a.toString(a,2)).reverse().toString(),2);

Lambda expression. Converts to binary representation, reverses, parses the string in base 2.

-5 bytes thanks to Poke!

-6 more bytes thanks to Poke!

-1, Poke has done more golfing on this than me by now.

share|improve this answer
    
Even though REPL submissions are allowed, they still follow the rule that you can't assume input is in predefined variables (like a in this context) – FlipTack 13 hours ago
    
@FlipTack Oops. It was originally a function before I remembered the repl existed – Pavel 13 hours ago
    
Well I suppose you can just do a-> at the start to make it a lambda expression and cut out the println. That might make it shorter. – FlipTack 13 hours ago
1  
Also, in the future, use print instead of println for golfing :) – FlipTack 13 hours ago
    
As far as I can tell, this prints the reverse binary string, rather than evaluating it as a new integer. – FlipTack 13 hours ago

Haskell, 36 bytes

0!b=b
a!b=div a 2!(b+b+mod a 2)
(!0)

Same algorithm (and length!) as ETHproductions’ JavaScript answer.

share|improve this answer

MATL, 4 bytes

BPXB

Try it online!

Explanation

B     % Input a number implicitly. Convert to binary array
P     % Reverse array
XB    % Convert from binary array to number. Display implicitly
share|improve this answer

Mathematica, 38 bytes

#+##&~Fold~Reverse[#~IntegerDigits~2]&
share|improve this answer

Pyth, 6 bytes

i_.BQ2

Test suite available here.

Explanation

i_.BQ2
    Q     eval(input())
  .B      convert to binary
 _        reverse
i    2    convert from base 2 to base 10
share|improve this answer

Groovy, 46 bytes

{0.parseInt(0.toBinaryString(it).reverse(),2)}
share|improve this answer
    
Does this take any input? – Titus 10 hours ago
1  
@Titus it refers to the argument given to a block IIRC – Cyoce 9 hours ago
    
I love how this is the same length as my Java answer - Java and groovy, unite! – FlipTack 8 hours ago

k, 18 bytes

{2/:|X@&|\X:0b\:x}

Example:

k){2/:|X@&|\X:0b\:x}6
3
share|improve this answer

Batch, 62 bytes

@set/an=%1/2,r=%2+%1%%2
@if %n% gtr 0 %0 %n% %r%*2
@echo %r%

Explanation: On the first pass, %1 contains the input parameter while %2 is empty. We therefore evaluate n as half of %1 and r as +%1 modulo 2 (the % operator has to be doubled to quote it). If n is not zero, we then call ourselves tail recursively passing in n and an expression that gets evaluated on the next pass effectively doubling r each time.

share|improve this answer

C#, 98 bytes

using System.Linq;using b=System.Convert;a=>b.ToInt64(string.Concat(b.ToString(a,2).Reverse()),2);
share|improve this answer

PHP, 44 bytes

for(;$n=&$argv[1];$n>>=1)$r+=$r+$n%2;echo$r;

iterative: while input has set bits, pop a bit from input and push it to output. Run with -nr.

reursive, 52 bytes

function r($n,$r=0){return$n?r($n>>1,$r*2+$n%2):$r;}

PHP, 36 bytes

<?=bindec(strrev(decbin($argv[1])));

using builtins: convert to base2, reverse string, convert to decimal
(same as Robert Lerner´s answer, but using a parameter)

share|improve this answer

Perl 5 (5.12+), 34 bytes

say oct"0b".reverse sprintf"%b",<>

(Input on stdin, output on stdout, requires -E or -M5.012 at no cost).

Straightforward but not all that short. Too bad "reverse" and "sprintf" are such weighty keywords.

oct is an odd legacy name; oct "123" gives the decimal equivalent of octal 123 as you'd expect, but oct "0x123" interprets its input as hex and oct "0b101" interprets it as binary.

share|improve this answer

C, 48 44 bytes

r;f(n){r=n&1;while(n/=2)r=2*r+n%2;return r;}

Previous 44 bytes solution:

r;f(n){r=0;while(n)r=2*(r+n%2),n/=2;return r/2;}

Ungolfed and usage:

r;
f(n){
 r=n&1;
  while(n/=2)
   r=2*r+n%2;
 return r;
}


main() {
#define P(x) printf("%d %d\n",x,f(x))
P(1);
P(2);
P(3);
P(4);
P(5);
P(6);
P(7);
P(8);
P(9);
P(10);
}
share|improve this answer

PHP, 29 bytes

<?=bindec(strrev(decbin(1)));

Try it online!

Explanation

Above evaluates "1", base converts to binary, performs string reversal,
converts back to base 10.
share|improve this answer
1  
Note, unless otherwise specified, you generally need to take input as a function parameter, STDIN, or command line parameter. I.e., replace 1 with $argv[1] or similar. – Alex Howansky 10 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.