35
\$\begingroup\$

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.

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

47 Answers 47

1
2
0
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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/… \$\endgroup\$ – Wheat Wizard Jan 6 '17 at 6:15
  • \$\begingroup\$ 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 \$\endgroup\$ – raznagul Jan 6 '17 at 17:18
0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ – James Jan 6 '17 at 21:53
  • \$\begingroup\$ 124 bytes \$\endgroup\$ – ceilingcat Feb 20 '20 at 1:18
0
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can use Long.parseLong and Long.toString to save a few bytes. \$\endgroup\$ – corvus_192 Jan 5 '17 at 20:16
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

SmileBASIC, 41 bytes

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

Basically a port of the C/Java versions.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can shave a couple of characters off this by including the 0b in the sprintf statement: say oct reverse sprintf"%bb0",<> \$\endgroup\$ – Xcali Oct 22 '17 at 3:07
0
\$\begingroup\$

Common Lisp, 52 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Julia, 32 bytes

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

gives a warning but still runs

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is 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. \$\endgroup\$ – caird coinheringaahing Oct 25 '17 at 20:00
  • \$\begingroup\$ 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) \$\endgroup\$ – EricShermanCS Oct 25 '17 at 20:07
0
\$\begingroup\$

RProgN 2, 6 bytes

2Bi2iB

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

REXX, 46 bytes

say x2d(b2x(reverse(trunc(x2b(d2x(arg(1)))))))
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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