What is the reverse (binary) bit number?

34

3

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.

juniorRubyist

Posted 2017-01-04T18:01:43.847

Reputation: 875

2

Does "reverse the bits" mean reverse its binary digits? Sometimes it can also mean invert every bit.

– ETHproductions – 2017-01-04T18:03:31.813

Yes. Sorry for being unclear. – juniorRubyist – 2017-01-04T18:04:01.210

This and this are veeeeery similar. – Geobits – 2017-01-04T18:10:04.207

OEIS A030101. – orlp – 2017-01-04T18:12:07.103

1"base 10" Any particular reason why? – CalculatorFeline – 2017-06-21T01:00:08.587

Thought I found a really weird property, but 9 broke it. For all examples other than nine, if you reverse the binary number and multiply ones by their index and sum... Then you take that sum and get the "ath prime", it works for all of the numbers that result in primes. – Magic Octopus Urn – 2017-10-25T13:54:40.673

Answers

20

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.

FlipTack

Posted 2017-01-04T18:01:43.847

Reputation: 13 242

2Beat you by 9 seconds. – mbomb007 – 2017-01-04T18:09:42.430

@mbomb007 I beat you a few seconds too I guess, but I made a small mistake so I deleted mine xP – busukxuan – 2017-01-04T18:10:17.767

4

@mbomb007 http://meta.codegolf.stackexchange.com/a/10812/14215

– Geobits – 2017-01-04T18:12:10.927

Oh, haven't seen that. That's a recent meta post. I disagree with it, though. – mbomb007 – 2017-01-04T18:12:44.387

6@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 – 2017-01-04T18:15:36.660

3Not 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 – 2017-01-04T18:17:01.477

Slower or not, it's leading in the vote count. – steenbergh – 2017-01-05T15:40:42.610

Probably because the sour grapes are amusing. At least for me. – Nick T – 2017-01-06T18:59:56.377

1@steenbergh Who cares? Same code, same score. – mbomb007 – 2017-02-02T19:35:35.417

17

Python, 29 bytes

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

Try it online

mbomb007

Posted 2017-01-04T18:01:43.847

Reputation: 21 944

1This is what I would have done. ;) – juniorRubyist – 2017-01-04T18:28:54.517

13

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

ETHproductions

Posted 2017-01-04T18:01:43.847

Reputation: 47 880

f=(n,q)=>n?f(n>>1,q*2|n%2):q almost works. But sadly not for n=0. – Arnauld – 2017-01-04T22:07:51.293

@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 – 2017-01-04T23:05:36.953

This is a late follow-up, but the input is now known to be always positive. – Arnauld – 2017-01-13T01:45:46.007

@Arnauld Thanks! – ETHproductions – 2017-01-18T14:34:37.733

10

Java 8, 53 47 46 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;}

Try it online!

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
};

FlipTack

Posted 2017-01-04T18:01:43.847

Reputation: 13 242

1Save 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 – 2017-01-04T22:28:21.650

2@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 – 2017-01-04T22:40:12.310

45 bytes (Changed t=t*2+ to t+=t+.) – Kevin Cruijssen – 2017-10-25T12:45:35.540

@KevinCruijssen nice one! – FlipTack – 2017-10-25T12:49:29.063

9

J, 6 bytes

|.&.#:

|. reverse

&. under

#: base 2

Adám

Posted 2017-01-04T18:01:43.847

Reputation: 37 779

8

Jelly, 3 bytes

BUḄ

Try it online!

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

Riley

Posted 2017-01-04T18:01:43.847

Reputation: 11 345

7That's pretty short, BUB – Cyoce – 2017-01-04T22:42:51.473

Hmm... Is that really 3 bytes? – aioobe – 2017-01-06T19:41:31.713

1

@aioobe Yep. Jelly uses it's own code page where each of these characters is 1 byte.

– Riley – 2017-01-06T19:43:48.243

Cool, thanks! <pad> – aioobe – 2017-01-06T21:32:02.537

8

Mathematica, 19 bytes

#~IntegerReverse~2&

ngenisis

Posted 2017-01-04T18:01:43.847

Reputation: 4 600

7

C, 48 44 43 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);
}

Karl Napf

Posted 2017-01-04T18:01:43.847

Reputation: 4 131

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 – 2017-01-05T08:19:25.270

1@gurka The function should be reusable. – Karl Napf – 2017-01-05T08:26:54.783

1I think that for loops are always at least as short as while loops, and often shorter. – anatolyg – 2017-01-05T20:00:31.180

@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 – 2017-01-05T22:01:52.263

Yes; also, turn = into += to make it shorter and more obfuscated – anatolyg – 2017-01-05T22:49:19.867

7

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.

C Anderson

Posted 2017-01-04T18:01:43.847

Reputation: 171

1Welcome 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 – 2017-01-05T23:48:47.067

1Did 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 – 2017-10-25T13:09:13.410

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 – 2017-10-25T13:12:38.277

5

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

Alexis Andersen

Posted 2017-01-04T18:01:43.847

Reputation: 591

@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 – 2017-01-04T22:46:37.630

Can you remove the parentheses in .to_i(2)? – Cyoce – 2017-01-05T15:48:20.933

@Cyoce sure enough, thanks. – Alexis Andersen – 2017-01-05T15:54:16.497

4

05AB1E, 3 bytes

bRC

Try it online!

Adnan

Posted 2017-01-04T18:01:43.847

Reputation: 41 965

4

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!

Pavel

Posted 2017-01-04T18:01:43.847

Reputation: 8 585

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 – 2017-01-04T18:24:50.050

@FlipTack Oops. It was originally a function before I remembered the repl existed – Pavel – 2017-01-04T18:25:55.847

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 – 2017-01-04T18:26:30.717

1Also, in the future, use print instead of println for golfing :) – FlipTack – 2017-01-04T18:26:44.180

As far as I can tell, this prints the reverse binary string, rather than evaluating it as a new integer. – FlipTack – 2017-01-04T18:39:04.197

@FlipTack I think it works now. Only gained a byte. – Pavel – 2017-01-04T18:55:56.333

Long.toString(a,2) saves 4 bytes over Long.toBinaryString(a) – Poke – 2017-01-04T19:32:08.523

1StringBuffer saves a byte over StringBuilder – Poke – 2017-01-04T19:33:12.677

@Poke Thanks, I appreciate it! – Pavel – 2017-01-04T19:35:46.163

a is of type Long so you should be able to use a.parseLong and a.toString. It will give a warning about using a static method in a non-static way or something but that's fine. Saves 6 bytes. – Poke – 2017-01-04T19:36:58.933

a.valueOf instead of a.parseLong should save a byte – Poke – 2017-01-04T19:38:34.853

1Could you do +"" instead of .toString()? – Cyoce – 2017-01-08T02:35:04.750

@Cyoce Was about to comment this, but then I saw yours at the bottom. +1 from me, that should definitely be possible for the empty .toString(). – Kevin Cruijssen – 2017-01-09T15:46:39.350

3

Japt, 5 3 bytes

-2 bytes thanks to Shaggy

¢ÔÍ

Try it online!

Oliver

Posted 2017-01-04T18:01:43.847

Reputation: 7 160

1Nice, exactly what I had. The ) could be a space too :-) – ETHproductions – 2017-01-04T18:17:19.937

This can now be ¢ÔÍ or ¤ÔÍ. – Shaggy – 2019-12-19T12:34:51.103

3

Perl 6, 19 bytes

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

Sean

Posted 2017-01-04T18:01:43.847

Reputation: 4 136

Where is the input? – Titus – 2017-01-04T21:54:55.143

This is a function that takes a single parameter $_. It isn't mentioned by name, but the base method is called on it. – Sean – 2017-01-04T22:40:58.340

2@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 – 2017-01-06T07:55:20.610

3

Bash/Unix utilities, 24 23 bytes

dc -e2i`dc -e2o?p|rev`p

Try it online!

Mitchell Spector

Posted 2017-01-04T18:01:43.847

Reputation: 3 392

A courageous take on Bash! – juniorRubyist – 2017-01-07T20:01:08.447

@juniorRubyist -- Thank you! – Mitchell Spector – 2017-01-07T21:55:53.673

3

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.

Lynn

Posted 2017-01-04T18:01:43.847

Reputation: 55 648

3

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;}

Titus

Posted 2017-01-04T18:01:43.847

Reputation: 13 814

@JörgHülsermann The 44 bytes have $r+=$r. But I actually don´t remember why I put that in front. – Titus – 2017-05-15T07:28:01.347

2

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

Luis Mendo

Posted 2017-01-04T18:01:43.847

Reputation: 87 464

2

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

Mike Bufardeci

Posted 2017-01-04T18:01:43.847

Reputation: 1 680

2

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
  )

corvus_192

Posted 2017-01-04T18:01:43.847

Reputation: 1 889

1

Mathematica, 38 bytes

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

JungHwan Min

Posted 2017-01-04T18:01:43.847

Reputation: 13 290

1

Groovy, 46 bytes

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

Magic Octopus Urn

Posted 2017-01-04T18:01:43.847

Reputation: 19 422

Does this take any input? – Titus – 2017-01-04T21:55:35.010

1@Titus it refers to the argument given to a block IIRC – Cyoce – 2017-01-04T22:47:22.593

I love how this is the same length as my Java answer - Java and groovy, unite!

– FlipTack – 2017-01-04T23:06:59.170

1@FlipTack I'm gonna go cry now. – Magic Octopus Urn – 2017-01-05T14:23:19.633

1

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

Luis Mendo

Posted 2017-01-04T18:01:43.847

Reputation: 87 464

1

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.

Neil

Posted 2017-01-04T18:01:43.847

Reputation: 95 035

1

C#, 98 bytes

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

Horváth Dávid

Posted 2017-01-04T18:01:43.847

Reputation: 679

1

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.

Billywob

Posted 2017-01-04T18:01:43.847

Reputation: 3 363

1

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.

FlipTack

Posted 2017-01-04T18:01:43.847

Reputation: 13 242

0

k, 18 bytes

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

Example:

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

skeevey

Posted 2017-01-04T18:01:43.847

Reputation: 4 139

0

Perl 5 (5.12+), 32 bytes

say oct reverse sprintf"%bb0",<>

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

hobbs

Posted 2017-01-04T18:01:43.847

Reputation: 2 403

1You can shave a couple of characters off this by including the 0b in the sprintf statement: say oct reverse sprintf"%bb0",<> – Xcali – 2017-10-22T03:07:06.093

0

Java 7, 94 89 bytes

Golfed:

int x(int n){return Long.parseLong(new StringBuffer(Long.toString(n,2)).reverse()+"",2)};

Ungolfed:

int x(int n)
{
    return Integer.parseInt(new StringBuffer(Integer.toString(n, 2)).reverse() + "", 2);
}

5 bytes saved thanks to @corvus_192

peech

Posted 2017-01-04T18:01:43.847

Reputation: 309

1You can use Long.parseLong and Long.toString to save a few bytes. – corvus_192 – 2017-01-05T20:16:30.567

0

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.

Deepak

Posted 2017-01-04T18:01:43.847

Reputation: 111

1

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 http://codegolf.stackexchange.com/questions/173/tips-for-code-golfing-in-c

– Post Rock Garf Hunter – 2017-01-06T06:15:56.013

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 – 2017-01-06T17:18:55.783

0

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.

mreff555

Posted 2017-01-04T18:01:43.847

Reputation: 111

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.

– James – 2017-01-06T21:53:41.170

124 bytes – ceilingcat – 2020-02-20T01:18:46.097

0

Pari/GP , 28 byte

The value to be "reversed" is expected in variable a; i.e. do a=37 first. Then execute the cmd. Because Pari/GP is interpreting you do not need to add an extra print(b) because referencing a variable or a result just prints it to the console:

  b=a%2;while(a\=2,b+=b+a%2);b

Example:

  a=37
  b=a%2;while(a\=2,b+=b+a%2);b
  \\ printed result is: 41                  

Try it online!

Gottfried Helms

Posted 2017-01-04T18:01:43.847

Reputation: 201

0

SmileBASIC, 41 bytes

INPUT N
WHILE N:T=T+T+N MOD 2N=N>>1WEND?T

Basically a port of the C/Java versions.

12Me21

Posted 2017-01-04T18:01:43.847

Reputation: 6 110

0

8th, 41 29 bytes

2 base drop >s rev >n decimal

Usage

ok> 37 2 base drop >s rev >n decimal .
41

Test case

: f 2 base drop >s s:rev >n decimal ; 
( dup . " => " . f . cr ) 1 10 loop

1 => 1
2 => 1
3 => 3
4 => 1
5 => 5
6 => 3
7 => 7
8 => 1
9 => 9
10 => 5

Chaos Manor

Posted 2017-01-04T18:01:43.847

Reputation: 521

0

Scala 47 bytes

Handles BigInt

((i:BigInt)=>BigInt(i.toString(2).reverse,2))([Number to Reverse])

if only we could:

(i=>BigInt(i.toString(2).reverse,2))([Number to Reverse])

or

(BigInt(_.toString(2).reverse,2))([Number to Reverse])

Example (REPL):

scala> ((i:Int)=>BigInt(i.toString(2).reverse,2))(100)
res1: scala.math.BigInt = 19

Example (in Situ):

object main extends App {
    val arg = Option(args).getOrElse(Array[String]("100"))
    (BigInt(arg(0)) to BigInt(arg(1))).map((n)=>
    (println(n + "-->" + BigInt(n.toString(2).reverse, 2))))
}

run:

run 20 30

result:

[debug] Waiting for thread run-main-23 to terminate.
20-->5
21-->21
22-->13
23-->29
24-->3
25-->19
26-->11
27-->27
28-->7
29-->23
30-->15
[debug]         Thread run-main-23 exited.

claydonkey

Posted 2017-01-04T18:01:43.847

Reputation: 31

0

C 41 bytes

g(i,r){for(r=0;r+=r+i%2,i/=2;);return r;}

Input in "i" output the result

Try it online!

RosLuP

Posted 2017-01-04T18:01:43.847

Reputation: 3 036

0

Common Lisp, 52 bytes

(parse-integer(reverse(format()"~b"(read))):radix 2)

Try it online!

Renzo

Posted 2017-01-04T18:01:43.847

Reputation: 2 260

0

Labyrinth, 22 bytes

_2/?+:{!
}    "
++:{%#

Try it online!

Explanation

The idea is to disassemble the input bit-by-bit while assembling the output from the other end. Luckily, it's easiest to deconstruct a number from the right, and build one up from the left, so this automatically reverses the bits. We'll generally be keeping what's left of the input on top the main stack, and what we've already computed of the result on top of the auxiliary stack.

_2/  When the program starts out, this doesn't really do anything, because it
     just divides an implicit zero by 2.
?+   Read an integer N from STDIN and add it to the implicit zero on top of 
     the stack.

     The main loop starts here:

:    Duplicate what's left of N. This is also used as the conditional to end
     the loop. Once this reaches zero, the IP moves straight ahead, exiting
     the loop. Otherwise, the IP turns south which continues the loop.
#    Push the stack depth, 2.
%    Take N modulo 2, i.e. get its least significant bit.
{    Fetch the intermediate result R from the auxiliary stack.
:+   Double it (shifting its existing bits left by one position).
+    Add the bit we just extracted from N to R.
}    Put R back on the auxiliary stack.
_2/  Divide N by 2, dropping its least significant bit.
?+   We're at EOF, so ? just pushes zero and the + gets rid of that zero.

     Then the main loop starts over.
     When we exit the loop (once N is zero), this bit is run:

{    Retrieve R from the auxiliary stack.
!    Print it.
     The IP hits a dead end and turns around.
{:+? Various shenanigans which simply leave a zero on top of the stack.
/    Terminates the program due to the attempted division by zero.

Martin Ender

Posted 2017-01-04T18:01:43.847

Reputation: 184 808

0

APL (Dyalog Unicode), 10 bytes

2⊥∘⊖2∘⊥⍣¯1

Try it!

Thanks to @Adám for 2 bytes.

How it works:

This is a tacit function. To use it, it has to be assigned a name (like f←) and then called over an input; for the test cases: f 1, f 2, etc.

2⊥∘⊖2∘⊥⍣¯1  # Main function; tacit.
       ⍣¯1  # invert
    2∘⊥     # convert from base 2 (which is inverted to 'convert to base 2')
  ∘⊖        # flip, then
2⊥          # convert from base 2 

J. Sallé

Posted 2017-01-04T18:01:43.847

Reputation: 3 233

0

Julia, 32 bytes

f(n)=parseint(reverse(bin(n)),2)

gives a warning but still runs

EricShermanCS

Posted 2017-01-04T18:01:43.847

Reputation: 121

1Is this a full program or a function, because it looks like a snippet? If this is a snippet, you can change it so that it conforms with our rules. – caird coinheringaahing – 2017-10-25T20:00:38.950

if you run this exact code on the interpreter it returns the value. If it must return using the return keyword, I will add that in. other than that, and input, this is a full program. just substitute n for any number (input was not specified in the rules, unless thats a default requirement) – EricShermanCS – 2017-10-25T20:07:46.763

0

Husk, 3 bytes

ḋ↔ḋ

Try it online!

Explanation

Here's an explanation, even if there's not much to it:

     -- implicit input N    | 10
  ḋ  -- convert to base2    | [1,0,1,0]
 ↔   -- reverse             | [0,1,0,1]
ḋ    -- convert from base2  | 5

ბიმო

Posted 2017-01-04T18:01:43.847

Reputation: 15 345

0

JavaScript, 44 bytes

f=i=>(a=0,(x=i=>i?(a=a*2+i%2,x(i>>1)):a)(i))

for(i=1;i<10;i++){console.log(i,f(i))}

Евгений Новиков

Posted 2017-01-04T18:01:43.847

Reputation: 987

0

Add++, 14 bytes

D,f,@,BBBR2@Bb

Try it online!

How it works

D,f,@,   - Create a monadic function named f. Example argument: [10]
      BB - Convert to binary;     STACK = ['1010']
      BR - Reverse the top value; STACK = ['0101']
      2  - Push 2;                STACK = ['0101' 2]
      @  - Reverse the stack;     STACK = [2 '0101']
      Bb - Convert from base;     STACK = [5]
         - Implicit return

caird coinheringaahing

Posted 2017-01-04T18:01:43.847

Reputation: 13 702

0

RProgN 2, 6 bytes

2Bi2iB

Try it online!

ATaco

Posted 2017-01-04T18:01:43.847

Reputation: 7 898

0

REXX, 46 bytes

say x2d(b2x(reverse(trunc(x2b(d2x(arg(1)))))))

idrougge

Posted 2017-01-04T18:01:43.847

Reputation: 641

0

Go, 49 bytes

A function literal based off my Java answer:

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

Try it online!

FlipTack

Posted 2017-01-04T18:01:43.847

Reputation: 13 242