# What is the reverse (binary) bit number?

So you are given a POSITIVE 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 is A030101 in the OEIS.

• Does "reverse the bits" mean reverse its binary digits? Sometimes it can also mean invert every bit. – ETHproductions Jan 4 '17 at 18:03
• Yes. Sorry for being unclear. – juniorRubyist Jan 4 '17 at 18:04
• This and this are veeeeery similar. – Geobits Jan 4 '17 at 18:10
• – orlp Jan 4 '17 at 18:12
• "base 10" Any particular reason why? – CalculatorFeline Jun 21 '17 at 1:00

# Python, 29 bytes

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


Try it online!

This is an anonymous, unnamed function which returns the result.

First, bin(n) converts the argument to a binary string. We would ordinarily reverse this with the slice notation [::-1]. This reads the string with a step of -1, i.e. backwards. However, binary strings in Python are prefixed with an 0b, and therefore we give the slicing's second argument as 1, telling Python to read backwards terminating at index 1, thus not reading indexes 1 and 0.

Now that we have the backwards binary string, we pass it to int(...) with the second argument as 2. This reads the string as a base 2 integer, which is then implicity returned by the lambda expression.

• Beat you by 9 seconds. – mbomb007 Jan 4 '17 at 18:09
• – Geobits Jan 4 '17 at 18:12
• @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 Jan 4 '17 at 18:15
• Not invalid, but definitely pointless. If I had been slower, I'd simply delete mine and post a comment on the faster one that I came up with it too. – mbomb007 Jan 4 '17 at 18:17
• @steenbergh Who cares? Same code, same score. – mbomb007 Feb 2 '17 at 19:35

# Python, 29 bytes

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


Try it online

• This is what I would have done. ;) – juniorRubyist Jan 4 '17 at 18:28

## JavaScript (ES6), 30 28 bytes

Saved 2 bytes thanks to @Arnauld

f=(n,q)=>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 a 32 byte solution that does the same thing:

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

• f=(n,q)=>n?f(n>>1,q*2|n%2):q almost works. But sadly not for n=0. – Arnauld Jan 4 '17 at 22:07
• @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 Jan 4 '17 at 23:05
• This is a late follow-up, but the input is now known to be always positive. – Arnauld Jan 13 '17 at 1:45
• @Arnauld Thanks! – ETHproductions Jan 18 '17 at 14:34

# Java 8, 534746 45 bytes

• -4 bytes thanks to Titus
• -1 byte thanks to Kevin Cruijssen

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+x%2;return t;}


This can be assigned with IntFunction<Integer> f = ..., and then called with f.apply(num). 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
};

• 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 Jan 4 '17 at 22:28
• @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 Jan 4 '17 at 22:40
• 45 bytes (Changed t=t*2+ to t+=t+.) – Kevin Cruijssen Oct 25 '17 at 12:45
• @KevinCruijssen nice one! – FlipTack Oct 25 '17 at 12:49

# J, 6 bytes

|.&.#:


|. reverse

&. under

#: base 2

# Jelly, 3 bytes

BUḄ


Try it online!

B   # convert to binary
U  # reverse
Ḅ # convert to decimal

• That's pretty short, BUB – Cyoce Jan 4 '17 at 22:42
• Hmm... Is that really 3 bytes? – aioobe Jan 6 '17 at 19:41
• @aioobe Yep. Jelly uses it's own code page where each of these characters is 1 byte. – Riley Jan 6 '17 at 19:43
• Cool, thanks! <pad> – aioobe Jan 6 '17 at 21:32

## Mathematica, 19 bytes

#~IntegerReverse~2&


# Labyrinth, 23 bytes

?_";:_2
:   %
@/2_"!


Well, this is awkward... this returns the reverse BINARY number... Thanks @Martin Ender for pointing out both my bug and my ID 10T error. So this doesn't work, I'll have to find another solution.

• Welcome to PPCG, and nice first post! Just completing a challenge in a language like Labyrinth can be very difficult. Around here, we usually prefix the first line of an answer with one or two hashes, to make it show as a header: # Labyrinth, 89 bytes – ETHproductions Jan 5 '17 at 23:48
• Did you accidentally omit a leading space from the second row? As it stands, the program would just bounce back and forth on the first line because the _ are on the junctions. – Martin Ender Oct 25 '17 at 13:09
• Unfortunately, I just noticed that this isn't valid regardless, because the challenge asks for the base-10 representation of the reversed number, not its binary representation. – Martin Ender Oct 25 '17 at 13:12

# C, 484443 42 bytes

-1 byte thanks to gurka and -1 byte thanks to anatolyg:

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


Previous 44 bytes solution:

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


Previous 48 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){
for(
r=n&1;
n/=2;
r+=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);
}

• Isn't r already initialized to zero here r;f(n){r=0;, e.g. the r=0; is unnecessary? Also minor typo: "Previous 48 bytes solution" – simon Jan 5 '17 at 8:19
• @gurka The function should be reusable. – Karl Napf Jan 5 '17 at 8:26
• I think that for loops are always at least as short as while loops, and often shorter. – anatolyg Jan 5 '17 at 20:00
• @anatolyg something like: r;f(n){for(r=n&1;n/=2;r=2*r+n%2);return r;}? 1 byte shorter, but I'm unsure if it's valid C (C99). – simon Jan 5 '17 at 22:01
• Yes; also, turn = into += to make it shorter and more obfuscated – anatolyg Jan 5 '17 at 22:49

# Ruby, 29 28 bytes

->n{("%b"%n).reverse.to_i 2}


"%b" % n formats the input n as a binary string, reverse, then convert back to a number

Usage/Test cases:

m=->n{("%b"%n).reverse.to_i 2}
m[1] #=> 1
m[2] #=> 1
m[3] #=> 3
m[4] #=> 1
m[5] #=> 5
m[6] #=> 3
m[7] #=> 7
m[8] #=> 1
m[9] #=> 9
m[10] #=> 5

• @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 Jan 4 '17 at 22:46
• Can you remove the parentheses in .to_i(2)? – Cyoce Jan 5 '17 at 15:48
• @Cyoce sure enough, thanks. – Alexis Andersen Jan 5 '17 at 15:54

# 05AB1E, 3 bytes

bRC


Try it online!

# Java (OpenJDK), 63 bytes

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


Try it online!

Thanks to poke for -12 bytes and to Cyoce for -8 bytes!

• 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 Jan 4 '17 at 18:24
• @FlipTack Oops. It was originally a function before I remembered the repl existed – Pavel Jan 4 '17 at 18:25
• Also, in the future, use print instead of println for golfing :) – FlipTack Jan 4 '17 at 18:26
• StringBuffer saves a byte over StringBuilder – Poke Jan 4 '17 at 19:33
• Could you do +"" instead of .toString()? – Cyoce Jan 8 '17 at 2:35

# Perl 6, 19 bytes

{:2(.base(2).flip)}

• Where is the input? – Titus Jan 4 '17 at 21:54
• This is a function that takes a single parameter $_. It isn't mentioned by name, but the base method is called on it. – Sean Jan 4 '17 at 22:40 • @Titus in Perl 6 a Block is a type of Code, which is to say it's a callable object. The above is an expression that you can take and assign to a variable like a function or lambda in another language, or call directly — {:2(.base(2).flip)}(10) at the REPL will print 5. So it meets the standard code-golf criteria for a function. – hobbs Jan 6 '17 at 7:55 # 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. # Bash/Unix utilities, 24 23 bytes dc -e2idc -e2o?p|revp  Try it online! • A courageous take on Bash! 😉 – juniorRubyist Jan 7 '17 at 20:01 • @juniorRubyist -- Thank you! – Mitchell Spector Jan 7 '17 at 21:55 # PHP, 33 bytes <?=bindec(strrev(decbin($argn)));


convert to base2, reverse string, convert to decimal. Save to file and run as pipe with -F.

no builtins:

iterative, 41 bytes

for(;$n=&$argn;$n>>=1)$r+=$r+$n%2;echo$r;  While input has set bits, pop a bit from input and push it to output. Run as pipe with -nR. recursive, 52 bytes function r($n,$r=0){return$n?r($n>>1,$r*2+$n%2):$r;}

• @JörgHülsermann The 44 bytes have $r+=$r. But I actually don´t remember why I put that in front. – Titus May 15 '17 at 7:28

# 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


# 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


## Japt, 5 bytes

¢w n2


Try it Online!

• Nice, exactly what I had. The ) could be a space too :-) – ETHproductions Jan 4 '17 at 18:17

# Scala, 40 bytes

i=>BigInt(BigInt(i)toString 2 reverse,2)


### Usage:

val f:(Int=>Any)=i=>BigInt(BigInt(i)toString 2 reverse,2)
f(10) //returns 5


### Explanation:

i =>          // create an anonymous function with a parameter i
BigInt(       //return a BigInt contructed from
BigInt(i)     //i converted to a BigInt
toString 2    //converted to a binary string
reverse       //revered
,
2             //interpreted as a binary string
)


# Mathematica, 38 bytes

#+##&~Fold~Reverse[#~IntegerDigits~2]&


# Groovy, 46 bytes

{0.parseInt(0.toBinaryString(it).reverse(),2)}

• Does this take any input? – Titus Jan 4 '17 at 21:55
• @Titus it refers to the argument given to a block IIRC – Cyoce Jan 4 '17 at 22:47
• I love how this is the same length as my Java answer - Java and groovy, unite! – FlipTack Jan 4 '17 at 23:06
• @FlipTack I'm gonna go cry now. – Magic Octopus Urn Jan 5 '17 at 14:23

# 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


## 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.

# C#, 98 bytes

using System.Linq;using b=System.Convert;a=>b.ToInt64(string.Concat(b.ToString(a,2).Reverse()),2);


## R, 55 bytes

sum(2^((length(y<-rev(miscFuncs::bin(scan()))):1)-1)*y)


Reads input from stdin and consequently uses the bin function from the miscFuncs package to convert from decimal to a binary vector.

# Pushy, 19 bytes

No builtin base conversion!

$&2%v2/;FL:vK2*;OS#  Try it online! Pushy has two stacks, and this answer makes use of this extensively. There are two parts two this program. First, $&2%v2/;F, converts the number to its reverse binary representation:

            \ Implicit: Input is an integer on main stack.
\$      ;    \ While i != 0:
&2%v       \   Put i % 2 on auxiliary stack
2/     \   i = i // 2 (integer division)
F   \ Swap stacks (so result is on main stack)


Given the example 10, the stacks would appear as following on each iteration:

1: [10]
2: []

1: [5]
2: [0]

1: [2]
2: [0, 1]

1: [1]
2: [0, 1, 0]

1: [0]
2: [0, 1, 0, 1]


We can see that after the final iteration, 0, 1, 0, 1 has been created on the second stack - the reverse binary digits of 10, 0b1010.

The second part of the code, L:vK2*;OS#, is taken from my previous answer which converts binary to decimal. Using the method decsribed and explained in that answer, it converts the binary digits on the stack into a base 10 integer, and prints the result.

# k, 18 bytes

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


Example:

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


# C#, 167 bytes

 for(int i = 1; i <= 10; i++)
{
var bytes= Convert.ToString(i, 2);
var value= Convert.ToInt32(byteValue.Reverse());
console.WriteLine(value);
}


Explanation:

Here I will iterate n values and each time iterated integer value is convert to byte value then reverse that byte value and that byte value is converted to integer value.

• Welcome to the site! I don't know much about C# but you most certainly have a good deal of extra whitespace I would recommend removing. It also is not clear how I/O is dealt with in this submission. It is standard to either write a function or to use STDIN (I think that is console.Read() but you would probably know better than I would) and STDOUT. Anyway, welcome to the site if you want more experienced advice in golfing C# I would recommend codegolf.stackexchange.com/questions/173/… – Sriotchilism O'Zaic Jan 6 '17 at 6:15
• I've downvoted this answer, because it doesn't work at all. .Reverse() returnes IEnumerable<char>. As Convert.ToInt32 doesn't have an overload for IEnumerable it throws an exception. Also the answer doesn't follow the rules for code golf: 1)As nothing is specified the submission has to be a full program or function not just a snippet. 2)using statements must be included in the byte count – raznagul Jan 6 '17 at 17:18

c/c++ 136 bytes

uint8_t f(uint8_t n){int s=8*sizeof(n)-ceil(log2(n));n=(n&240)>>4|(n&15)<<4;n=(n&204)>>2|(n&51)<<2;n=(n&172)>>1|(n&85)<<1;return(n>>s);}


It's not going to win, but I wanted to take a different approach in c/c++ 120 bytes in the function

#include <math.h>
#include <stdio.h>
#include <stdint.h>

uint8_t f(uint8_t n){
int s=8*sizeof(n)-ceil(log2(n));
n=(n&240)>>4|(n&15)<<4;
n=(n&204)>>2|(n&51)<<2;
n=(n&172)>>1|(n&85)<<1;
return (n>>s);
}

int main(){
printf("%u\n",f(6));
return 0;
}


To elaborate on what I am doing, I used the log function to determine the number of bits utilized by the input. Than a series of three bit shifts left/right, inside/outside, even/odd which flips the entire integer. Finally a bit shift to shift the number back to the right. Using decimals for bit shifts instead of hex is a pain but it saved a few bytes.

• You do need to include the function declaration, so this is actually 163 bytes. Although, if you remove the extraneous whitespace, you could shorten it to 136. – DJMcMayhem Jan 6 '17 at 21:53