Binary to decimal converter

32

2

Binary to decimal converter

As far as I can see, we don't have a simple binary to decimal conversion challenge.


Write a program or function that takes a positive binary integer and outputs its decimal value.

You are not allowed to use any builtin base conversion functions. Integer-to-decimal functions (e.g., a function that turns 101010 into [1, 0, 1, 0, 1, 0] or "101010") are exempt from this rule and thus allowed.

Rules:

  • The code must support binary numbers up to the highest numeric value your language supports (by default)
  • You may choose to have leading zeros in the binary representation
  • The decimal output may not have leading zeros.
  • Input and output formats are optional, but there can't be any separators between digits. (1,0,1,0,1,0,1,0) is not a valid input format, but both 10101010 and (["10101010"]) are.
    • You must take the input in the "normal" direction. 1110 is 14 not 7.

Test cases:

1
1

10
2

101010
42

1101111111010101100101110111001110001000110100110011100000111
2016120520371234567

This challenge is related to a few other challenges, for instance this, this and this.

Stewie Griffin

Posted 2016-12-05T19:37:45.340

Reputation: 43 471

Related – mbomb007 – 2016-12-05T19:43:30.143

Does the output have to be unsigned or can it be signed? Also, if my language happens to automatically switch between 32-bit and 64-bit integers depending on the length of the value, can the output be signed in both ranges? Eg- There's two binary values that will convert to decimal -1 (32 1's and 64 1's) – milk – 2016-12-05T20:47:33.717

Also, can the output be floating, do does it need to be an integer? – Carcigenicate – 2016-12-05T21:17:53.117

@Carcigenicate It must be an integer, but it can be of any data type. As long as round(x)==x you're fine :) 2.000 is accepted output for 10. – Stewie Griffin – 2016-12-05T21:31:46.760

Oh sweet. Thanks. – Carcigenicate – 2016-12-05T21:33:57.583

@milk, you may output +42 instead of 42 if you want to. If the language support 64-bit integers without any special type casting or importing then it should behave the same for all numbers from 1 to 2^64-1. – Stewie Griffin – 2016-12-05T21:35:25.393

Can I take two parameters (the number of bits, followed by the list of bits)? Otherwise, running a COW program will run for several minutes for anything larger than 1000000 and several hours for anything with only a couple more bits – Gabriel Benamy – 2016-12-06T21:09:49.670

The last number is the date the challenge was posted? The hours and seconds don't correspond with SE's UTC+0 time, it should be 20161205193745***** :) – RudolfJelin – 2016-12-07T19:52:42.370

I knew that comment would come sooner or later... Who cares about UTC+0? :) – Stewie Griffin – 2016-12-08T16:05:11.647

Answers

56

Jelly, 5 bytes

DḤ+¥/

Try it online!

Explanation

enter image description here

The cast

  • D is a monad (single argument function): digits, turning 1234 into [1, 2, 3, 4].

  • is a monad that doubles its single argument.

  • + is a dyad (two argument function) that adds its left and right arguments.

From there, it gets a little tricky.

Here’s what happens at parse time

  • D, , and + are read. The chain looks like [D, Ḥ, +].

  • The next two characters are quicks, which act like parse-time postfix operators on the links (functions) we've read so far.

  • When ¥ is read, the last two links get popped and replaced by a link that acts like the dyad formed by composing them. So now the chain looks like [D, dyad(Ḥ+)].

  • When / is read, the last link (which ought to be a dyad) gets popped and replaced by a monad that folds using this dyad (intuitively: f/ takes a list, replaces the commas in it with f, and evaluates the result.)

  • The final chain looks like [D, fold(dyad(Ḥ+))], two monads.

Here's what happens at run time

  • Input (a number) is implicitly read into the working value (say, 101010).

  • D is executed, replacing the working value with its digits ([1,0,1,0,1,0]).

  • fold(dyad(Ḥ+)) is executed, replacing the working value with 1∗0∗1∗0∗1∗0, where is the dyad Ḥ+.

So what does x∗y evaluate to?

  • In a dyadic definition, the working value is initially the left argument, x.

  • , the double monad, doubles this value. The working value is now 2x.

  • +, the plus dyad, lacks a right argument, so this is a hook: a special syntactical pattern where the right argument of this dyad gets injected into +. This yields 2x + y as the final working value, which is returned.

So the whole expression evaluates to:

1∗0∗1∗0∗1∗0 = 2×(2×(2×(2×(2×1+0)+1)+0)+1)+0
            = 32×1 + 16×0 + 8×1 + 4×0 + 2×1 + 1×0
            = 42

Lynn

Posted 2016-12-05T19:37:45.340

Reputation: 55 648

10Your explanations are getting better and better :-) – Luis Mendo – 2016-12-06T01:22:38.970

2Heh, I guess you do it from now on? That's awesome, +1. – Erik the Outgolfer – 2016-12-06T12:57:36.470

4I think this is the first piece of Jelly I've ever understood. +1! – Blue – 2016-12-07T19:59:24.980

Bravo. I actually understand what I initially thought was just a mess of seemingly random characters. Wonderful explanation. – swinefish – 2016-12-08T07:18:47.833

Amazing, but in what encoding is that 5 bytes? Ḥ (U+1E24) is 3 bytes in UTF8 for a total of 7 bytes. If UTF16, then this is 10 bytes. – Mark – 2016-12-09T21:51:04.013

1

@Mark Jelly has its own codepage to make the programs look, ahem, readable, but the programs could as well just be bytestrings.

– Lynn – 2016-12-10T13:10:54.140

20

Python 2, 49 37 31 30 Bytes

Now this will take a binary number in a decimal representation, since Python can handle arbitrarily large integers.

b=lambda n:n and n%2+2*b(n/10)

thanks to xnor for saving a byte :)

The easiest way to see how this works is by seeing a basic formula for converting binary to decimal:

= 101010 
= 1*(2^5) + 0*(2^4) + 1*(2^3) + 0*(2^2) + 1*(2^1) + 0*(2^0)
= 1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 0*1
= 42

This is a 'standard' way of converting. You can expand the third line like so:

= ((((1*2 + 0)*2 + 1)*2 + 0)*2 + 1)*2 + 0

And this is essentially what the recursive method I've made is doing.

Alternate solutions I had:

b=lambda n:n and n%10+2*b(n/10)
b=lambda n:n%10+2*(n and b(n/10))
b=lambda n:0if n<1else n%10+2*b(n/10)
b=lambda n:0**(n/10)or n%10+2*b(n/10)
b=lambda n,o=0:o*(n<'0')or b(n[1:],2*o+int(n[0]))
lambda j:sum(int(b)*2**a for a,b in enumerate(j,1))

Kade

Posted 2016-12-05T19:37:45.340

Reputation: 7 463

6You can do n%5 or n%2 instead of n%10. – xnor – 2016-12-05T22:02:13.870

@xnor Ah, not sure how I missed that! Thanks :) – Kade – 2016-12-06T01:37:47.587

12

05AB1E, 6 bytes

Code:

$¦v·y+

For the explantion, let's take the example 101010. We start with the number 1 (which is represented by the first digit). After that, we have two cases:

  • If the digit is a 0, multiply the number by 2.
  • If the digit is a 1, multiply the number by 2 and add 1.

So for the 101010 case, the following is calculated:

  • 101010, start with the number 1.
  • 101010, multiply by two, resulting into 2.
  • 101010, multiply by two and add one, resulting into 5.
  • 101010, multiply by two, resulting into 10.
  • 101010, multiply by two and add one, resulting into 21.
  • 101010, multiply by two, resulting into 42, which is the desired result.

Code explanation:

$         # Push 1 and input
 ¦        # Remove the first character
  v       # For each character (starting with the first)
   ·      #   Multiply the carry number by two
    y+    #   Add the current character (converted automatically to a number)

Uses the CP-1252 encoding. Try it online!

Adnan

Posted 2016-12-05T19:37:45.340

Reputation: 41 965

Nice one! (doesn't work for 0 though I just noticed) – Emigna – 2016-12-05T20:07:42.093

@Emigna Yep, luckily your code only needs to work for positive binary numbers. – Adnan – 2016-12-05T20:08:23.933

Didn't even see that part. Very nice then :) – Emigna – 2016-12-05T20:09:22.283

9

Haskell, 16 111 + 57 = 168 bytes

import Data.String
instance IsString[Int]where fromString=map((-48+).fromEnum)
f::[Int]->Int
f=foldl1((+).(2*))

+57 bytes for the compile flags -XOverloadedStrings, -XOverlappingInstances and -XFlexibleInstances.

The challenge has some cumbersome IO format, because it heavily depends on how data types are expressed in the source code. My first version (16 bytes), namely

foldl1((+).(2*))

takes a list of integers, e.g. [1,0,1,0,1,0] and was declared invalid because literal Haskell lists happen to have , between the elements. Lists per se are not forbidden. In my new version I use the very same function, now named f, but I overload "Quote enclosed character sequences". The function still takes a list of integers as you can see in the type annotation [Int] -> Int, but lists with single digit integers can now be written like "1234", e.g.

f "101010"

which evaluates to 42. Unlucky Haskell, because the native list format doesn't fit the challenge rules. Btw, f [1,0,1,0,1,0] still works.

nimi

Posted 2016-12-05T19:37:45.340

Reputation: 34 639

2Unfortunately a list is not a valid input. – Jonathan Allan – 2016-12-05T20:43:21.193

@JonathanAllan: Why? And if so, how should it take input at all? In Haskell a string is just a list of characters. – nimi – 2016-12-05T21:04:58.640

I don't know why ...but I enquired about this early on and an edit was made to add "(1,0,1,0,1,0,1,0) is not a valid input format, but both 10101010 and (["10101010"]) are." furthermore a comment suggests the array of characters is acceptable if that is how a string input is interpreted.

– Jonathan Allan – 2016-12-05T21:10:33.163

@JonathanAllan: my function takes a list. Lists don't have , between the elements. String representations of literal lists have , between the elements, but there are other ways where lists can come from, e.g. return values of other functions. As we don't have to take input of type string, no string representation is involved. let list = "abc" >> fromEnum.not <$> [False ..] in foldl1((+).(2*)) list also evaluates to 42. The intermediate list list is never turned into a string, so there are no separators like , involved. – nimi – 2016-12-05T21:26:45.570

A list is inherently separated, it was not just the character , that was banned. I asked if lists were OK and the response was a comment saying the edit had been made (including "there can't be any separators between digits"), which I understood to be "No"; maybe I misunderstood, maybe @StewieGriffin could let me know. – Jonathan Allan – 2016-12-05T22:23:21.453

1@JonathanAllan: any "binary integer" (the input we have to take) is inherently separated, it's a sequence of powers of 2. The restriction is about explicit separators (between the digits) and not about separation. Somehow I have to take separated digits. – nimi – 2016-12-05T22:56:31.850

Note how other answers are using extra bytes to take strings or decimal representations over lists, including Lynn's Jelly answer (in Jelly a string is also just a list of characters), which would be 4 bytes not 5 with Ḥ+¥/ rather than DḤ+¥/. – Jonathan Allan – 2016-12-05T23:04:48.600

@JonathanAllan: the rules, as written, do not forbid lists or lists of integers, just sequences that contain additional separators between the digits. My claim as discussed above: lists don't contain separators per se. Of course the elements (here: binary digits) are separated, because we have a few of them. For example, the string "1,0,1" is not allowed, because it has 5 characters but only 3 digits - the other two characters are separators. -- PS: last post for today, it's already late here. – nimi – 2016-12-05T23:43:06.727

2Op here: if it's possible to input 10101010 , "10101010" or something similar and make it work then the submission is valid. You may call it a string, list, integer or whatever. Inputting [1][0][1][0] or [1,0,1,0] is not ok. Basically, it should be possible to just hit a bunch of ones and zeros in a row somewhere. Is this clear? – Stewie Griffin – 2016-12-06T09:55:13.783

@StewieGriffin: better, now? – nimi – 2016-12-06T21:15:57.560

7

Retina, 15 bytes

Converts from binary to unary, then unary to decimal.

1
01
+`10
011
1

Try it online

mbomb007

Posted 2016-12-05T19:37:45.340

Reputation: 21 944

You are not allowed to use any builtin base conversion functions. ~OP – Roman Gräf – 2016-12-05T20:15:45.723

10@RomanGräf There aren't any. I was simply describing the process of my solution. – mbomb007 – 2016-12-05T20:25:14.097

7

PHP, 44 bytes

for(;""<$c=$argv[1][$i++];)$n+=$n+$c;echo$n;

I could have sworn that I´ve seen that question before. But well.

Reads the number from left to right, shifts left and adds the current bit.

Titus

Posted 2016-12-05T19:37:45.340

Reputation: 13 814

7

JavaScript (ES6), 33 31 bytes

s=>[...s].map(c=>r+=+c+r,r=0)|r

Edit: Shorter but less sweet: 2 bytes saved thanks to @ETHproductions.

Neil

Posted 2016-12-05T19:37:45.340

Reputation: 95 035

As is often the case, .map is shorter: s=>[...s].map(c=>+c+r+r,r=0)|r – ETHproductions – 2016-12-06T23:10:21.793

@ETHproductions How does your function return anything other than 0? – Neil – 2016-12-07T00:43:14.097

Sorry, it should be s=>[...s].map(c=>r+=+c+r,r=0)|r – ETHproductions – 2016-12-07T00:52:45.550

7

Labyrinth, 17 15 bytes

-+:
8 +
4_,`)/!

Try it online!

Image of the code

Labyrinth is a two-dimensional, stack-based language. In labyrinth, code execution follows the path of the code like a maze with spaces acting as walls and beginning at the top-left-most non-space character. The code flow is determined by the sign of the top of the stack. Since the stack has implicit zeroes at the bottom, the first four instructions (-+:+) have no effect.

Loop starting at the ,

  • , Push the ascii code value of the next input character to the stop of the stack, or push -1 if EOF.
  • _48 pushes 48 to the top of the stack
  • - Pop y, pop x, push x-y. The previous instructions have the effect of subtracting 48 from the input yielding 0 for "0" and 1 for "1".
  • + Pop y, pop x, push x+y.
  • : Duplicate the top of the stack
  • + This and the previous instruction have the effect of multiplying the current value by 2

So the circular part of the code, in effect, multiples the current number by 2 and adds either a 1 or a 0 depending on if the character 1 or 0 was input.

Tail

If the top of the stack is negative (meaning EOF was found), the code will turn left at the junction (going towards the semicolon).

  • ``` Negate the top of the stack to get 1
  • ) Icrement the top of the stack to get 2
  • / Pop y, pop x, push x/y (integer division). This has the effect of undoing the last *2 from the loop.
  • ! Output the integer representation of the top of the stack. At this point the program turns around because it hit a dead end and then exits with an error because it tries to divide by zero.

Thanks to @Martin Ender for saving me 2 bytes (and teaching me how to better think in Labyrinth).

Robert Hickman

Posted 2016-12-05T19:37:45.340

Reputation: 661

Instead of _48- you can simply do #% but unfortunately I don't see how it might help with the byte count. – Martin Ender – 2016-12-07T20:51:22.000

You can save a byte with \)instead of;_2` though. – Martin Ender – 2016-12-07T20:52:11.560

@MartinEnder, I don't understand your comment about #%. Can you explain how that works as a replacement for _48- to convert from ascii to int. Thanks for the ) tip. I'll make that change. – Robert Hickman – 2016-12-07T21:22:50.670

At that point in your program there are always two values on the stack so # is just short for _2. While _2% isn't a general conversion method for ASCII to integer, it works here because you're only interested in the first two digits as possible input. An alternative would be _1& (since modulo 2 simply extracts the least significant bit). – Martin Ender – 2016-12-07T21:28:52.840

Oh. That's brilliant. But yeah I'm not sure how to use that substitution (#%) to shorten the code overall. – Robert Hickman – 2016-12-07T21:33:56.357

The only possibility I can think of is decomposing the main loop into multiple 2x2 loops, which can often save bytes but is also usually very tricky. Not sure whether it's possible here. – Martin Ender – 2016-12-07T21:36:12.050

Btw you also don't need the @. The / is going to terminate the program for you after the IP turns around. – Martin Ender – 2016-12-07T21:36:46.137

6

Brain-Flak, 46, 28 bytes

([]){{}({}<>({}){})<>([])}<>

Try it online!

Many many bytes saved thanks to @Riley!

Since brain-flak can't take binary input, input is a list of '0's and '1's.

Explanation:

#Push the height of the stack
([])

#While true:
{

 #Pop the height of the stack
 {}

 #Push this top number to (the other stack * 2)
 ({}<>({}){})

 #Toggle back on to the main stack
 <>

 #Push the new height of the stack
 ([])

#endwhile
}

#Toggle back to the other stack, implicitly display.
<>

James

Posted 2016-12-05T19:37:45.340

Reputation: 54 537

Love the explanation! So hard to read brain-flak without it :) – Emigna – 2016-12-05T20:08:26.010

2^. I can't even read my own programs if I don't leave myself a few comments. – Riley – 2016-12-05T20:10:28.010

You can get it down to 32 bytes by getting rid of the whole if part,and for the step "add number to other stack" just add it to the (other stack)*2. ([]){({}[()]<({}<>({}){})><>)}<> – Riley – 2016-12-05T20:16:38.267

And you can save another 4 by just popping at the start of the while and pushing the height again at the end. ([]){{}({}<>({}){})<>([])}<> – Riley – 2016-12-05T20:18:15.513

@Riley Oh my gosh, that's genius. Thankyou very much! – James – 2016-12-05T20:20:38.093

6

Java, 84 79 46 48 bytes

  • Version 3.1

Changed to long/48 bytes:

s->{long x=0;for(char c:s)x=c-48l+x*2;return x;}
  • Version 3.0

Did some golfing/46 bytes:

s->{int x=0;for(char c:s)x=c-48+x*2;return x;}
  • Version 2.0

Thanks to @Geobits!/79 bytes:

s->{int i=Math.pow(2,s.length-1),j=0;for(char c:s){j+=c>48?i:0;i/=2;}return j;}
  • Version 1.0

84 bytes:

s->{for(int i=-1,j=0;++i<s.length;)if(s[i]>48)j+=Math.pow(2,s.length-i+1);return j;}

Roman Gräf

Posted 2016-12-05T19:37:45.340

Reputation: 2 915

1guess i should have done an iterative solution. lulz. good job – Poke – 2016-12-05T20:46:59.760

Is your input type List<Character> or String? If it's the latter, I was unaware Java8 could do that! If it's the former is that allowed by the challenge? – Poke – 2016-12-05T21:00:05.880

s should be char[]. I hope that's allowed... – Roman Gräf – 2016-12-05T21:01:38.727

What is the return type here? I think it should be long because "The code must support binary numbers up to the highest numeric value your language supports" per the OP but for smaller values I would think it returns an int – Poke – 2016-12-05T21:02:20.847

I think char[] is generally allowed as a String representation. I was just unsure because of the clarification in the OP – Poke – 2016-12-05T21:03:06.403

It returns an int. I think it costs 2 bytes to change to long. – Roman Gräf – 2016-12-05T21:03:12.810

1

Probably fine on input type per this. Might want to take the 2 byte hit for output imo

– Poke – 2016-12-05T21:09:18.407

Just FYI, we can view the edit history to see previous versions of the code. You don't need to keep them all in your answer. – mbomb007 – 2016-12-05T21:32:40.353

4

Javascript (ES7) 41 40 36 bytes

f=([c,...b])=>c?c*2**b.length+f(b):0

takes a string as input

Shaved a byte thanks to ETHproductions

f=([c,...b])=>c?c*2**b.length+f(b):0
document.write([
    f('101010'),
    f('11010'),
    f('10111111110'),
    f('1011110010110'),
].join("<br>"))

Shaun H

Posted 2016-12-05T19:37:45.340

Reputation: 732

1

The right-to-left associativity of ** is weird, but nice job using it here. 1<<b.length would do the same thing, but it would require parentheses to keep from being parsed as (c*1)<<(b.length+...). I think you can save a byte by replacing b[0] with b+b (see here).

– ETHproductions – 2016-12-06T15:09:57.917

4

C# 6, 85 37 36 bytes

long b(long n)=>n>0?n%2+2*b(n/10):0;
  • Thanks to Kade for saving 41 bytes!
  • Changing to C# 6 saved another 7 bytes.

Yytsi

Posted 2016-12-05T19:37:45.340

Reputation: 3 582

Maybe this could provide some inspiration? ;)

– Kade – 2016-12-05T21:43:49.400

@Kade It does, thanks! I was looking at the Python answer which uses the same technique at the same moment you linked that :D I can get even shorter with C# 6. – Yytsi – 2016-12-05T21:47:58.797

4

Befunge-98, 12 bytes

2j@.~2%\2*+

Try it online!

Reads one char at a time from input, converts it to 0 or 1 by taking its value modulo 2 (0 is char(48), 1 is char(49)), then uses the usual algorithm of doubling the current value and adding the new digit each time.

Bonus: This works with any kind of input string, I've been trying for a while now to find any funny input->output combination, but I wasn't able to produce anything (sadly, "answer"=46). Can you?

Leo

Posted 2016-12-05T19:37:45.340

Reputation: 8 482

LOL. I was playing the same game with my answer. Most interesting number I could generate was 666.

– James Holderness – 2016-12-06T12:27:07.993

Nice one! I hadn't managed to find anything fitting for 666 :D It would be a lot easier if capitalization had an effect on values... – Leo – 2016-12-06T14:01:17.917

@James Holderness - I've been doing the same and I've only found 'theleapyear' to bring back 366, yours is really good. – Teal pelican – 2016-12-06T14:19:40.770

3

05AB1E, 7 bytes

RvNoy*O

Try it online!

Explanation

R         # reverse input
 v     O  # sum of
  No      # 2^index
     *    # times
    y     # digit

Emigna

Posted 2016-12-05T19:37:45.340

Reputation: 50 798

3

Perl, 25 bytes

-3 bytes thanks to @Dom Hastings.

24 bytes of code + 1 byte for -p flag.

$\|=$&<<$v++while s/.$//

To run it:

perl -pe '$\|=$&<<$v++while s/.$//' <<< 101010

Explanations:

$\|=$&<<$v++  # Note that: we use $\ to store the result
              # at first $v=0, and each time it's incremented by one
              # $& contains the current bit (matched with the regex, see bellow)
              # So this operation sets a $v-th bit of $\ to the value of the $v-th bit of the input
while         # keep doing this while...
s/.$//        #  ... there is a character at the end of the string, which we remove.
         # $\ is implicitly printed thanks to -p flag

Dada

Posted 2016-12-05T19:37:45.340

Reputation: 8 279

3

C, 53

v(char*s){int v=0,c;while(c=*s++)v+=v+c-48;return v;}

Same as my javascript answer

Test Ideone

edc65

Posted 2016-12-05T19:37:45.340

Reputation: 31 086

You can save 4 bytes by declaring v and c as global variables (though you need to change the name of v, since it's already the name of the function) like this: w=0;c;v(char*s){while(c=*s++)w+=w+c-48;return w;} – Steadybox – 2016-12-06T19:55:40.333

@Steadybox it could be w,c; but I don't want use globals when the answer is a function (even in code-golf) – edc65 – 2016-12-06T20:24:01.247

@Steadybox Globals defaults to 0 as well, so you can drop the =0. – algmyr – 2016-12-08T01:22:03.703

3

Retina, 12 bytes

Byte count assumes ISO 8859-1 encoding.

+%`\B
¶$`:
1

Try it online!

Alternative solution:

+1`\B
:$`:
1

Explanation

This will probably be easier to explain based on my old, less golfed, version and then showing how I shortened it. I used to convert binary to decimal like this:

^
,
+`,(.)
$`$1,
1

The only sensible way to construct a decimal number in Retina is by counting things (because Retina has a couple of features that let it print a decimal number representing an amount). So really the only possible approach is to convert the binary to unary, and then to count the number of unary digits. The last line does the counting, so the first four convert binary to unary.

How do we do that? In general, to convert from a list of bits to an integer, we initialise the result to 0 and then go through the bits from most to least significant, double the value we already have and add the current bit. E.g. if the binary number is 1011, we'd really compute:

(((0 * 2 + 1) * 2 + 0) * 2 + 1) * 2 + 1 = 11
           ^        ^        ^        ^

Where I've marked the individual bits for clarity.

The trick to doing this in unary is a) that doubling simply means repeating the number and b) since we're counting the 1s at the end, we don't even need to distinguish between 0s and 1s in the process. This will become clearer in a second.

What the program does is that it first adds a comma to the beginning as marker for how much of the input we've already processed:

^
,

Left of the marker, we'll have the value we're accumulating (which is correctly initialised to the unary representation of zero), and right of the value will be the next bit to process. Now we apply the following substitution in a loop:

,(.)
$`$1,

Just looking at ,(.) and $1,, this moves the marker one bit to the right each time. But we also insert $`, which is everything in front of the marker, i.e. the current value, which we're doubling. Here are the individual steps when processing input 1011, where I've marked the result of inserting $` above each line (it's empty for the first step):

,1011

1,011
 _
110,11
   ___
1101101,1
       _______
110110111011011,

You'll see that we've retained and doubled the zero along with everything else, but since we're disregarding them at the end, it doesn't matter how often we've doubled them, as long as the number of 1s is correct. If you count them, there are 11 of them, just what we need.

So that leaves the question of how to golf this down to 12 bytes. The most expensive part of the 18-byte version is having to use the marker. The goal is to get rid of that. We really want to double the prefix of every bit, so a first idea might be this:

.
$`$&

The problem is that these substitutions happen simultaneously, so first bit doesn't get doubled for each bit, but it just gets copied once each time. For input 1011 we'd get (marking the inserted $`):

 _ __ ___
1101011011

We do still need to process the input recursively so that the doubled first prefix is doubled again by the second and so on. One idea is to insert markers everywhere and repeatedly replace them with the prefix:

\B
,
+%`,
¶$`

After replacing each marker with the prefix for the first time, we need to remember where the beginning of the input was, so we insert linefeeds as well and use the % option to make sure that the next $` only picks up things up the closest linefeed.

This does work, but it's still too long (16 bytes when counting 1s at the end). How about we turn things around? The places where we want to insert markers are identified by \B (a position between two digits). Why don't we simply insert prefixes into those positions? This almost works, but the difference is that in the previous solution, we actually removed one marker in each substitution, and that's important to make the process terminate. However, the \B aren't character but just positions, so nothing gets removed. We can however stop the \B from matching by instead inserting a non-digit character into this place. That turns the non-word boundary into a word boundary, which is the equivalent of removing the marker character earlier. And that's what the 12-byte solution does:

+%`\B
¶$`:

Just for completeness, here are the individual steps of processing 1011, with an empty line after each step:

1
1:0
10:1
101:1

1
1:0
1
1:0:1
1
1:0
10:1:1

1
1:0
1
1:0:1
1
1:0
1
1:0:1:1

Again, you'll find that the last result contains exactly 11 1s.

As an exercise for the reader, can you see how this generalises quite easily to other bases (for a few additional bytes per increment in the base)?

Martin Ender

Posted 2016-12-05T19:37:45.340

Reputation: 184 808

3

Pushy, 10 bytes

Takes input as a list of 0/1 on the command line: $ pushy binary.pshy 1,0,1,0,1,0.

L:vK2*;OS#

The algorithm really shows the beauty of having a second stack:

            \ Implicit: Input on stack
L:    ;     \ len(input) times do:
  v         \   Push last number to auxiliary stack
   K2*      \   Double all items
       OS#  \ Output sum of auxiliary stack

This method works because the stack will be doubled stack length - n times before reaching number n, which is then dumped into the second stack for later. Here's what the process looks like for input 101010:

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

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

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

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

1: [16,0]
2: [2,0,8]

1: [32]
2: [2,0,8,0]

1: []
2: [2,0,8,0,32]

2 + 8 + 32 -> 42

FlipTack

Posted 2016-12-05T19:37:45.340

Reputation: 13 242

3

Matlab, 30 Bytes

@(x)sum(2.^find(flip(x)-48)/2)

The last test case has rounding errors (because of double), so if you need full precision:

@(x)sum(2.^uint64(find(flip(x)-48))/2,'native')

with 47 Bytes.

Jonas

Posted 2016-12-05T19:37:45.340

Reputation: 177

I can't test this, but I believe @(x)sum(2.^(find(flip(x)-48)-1)) will give the correct result for all cases for 32 bytes. flip works like fliplr if x is one dimensional. – Stewie Griffin – 2016-12-06T16:51:51.163

Nice solution! I also ran into the rounding error, thanks for the fix. What is the format of x? Calling flip or fliplr on a number just returns that number. – MattWH – 2016-12-10T01:35:31.550

x is the binary string, so call it with f=@(x)..; f('1111001010'). – Jonas – 2016-12-10T13:38:27.947

2

PowerShell v2+, 55 bytes

param($n)$j=1;$n[$n.length..0]|%{$i+=+"$_"*$j;$j*=2};$i

Feels too long ... Can't seem to golf it down any -- tips appreciated.

Explanation

param($n)$j=1;$n[$n.length..0]|%{$i+=+"$_"*$j;$j*=2};$i
param($n)$j=1;                                          # Take input $n as string, set $j=1
              $n[$n.length..0]                          # Reverses, also converts to char-array
                              |%{                  };   # Loop over that array
                                 $i+=+"$_"*$j;          # Increment by current value of $j times current digit
                                              $j*=2     # Increase $j for next loop iteration
                                                     $i # Leave $i on pipeline
                                                        # Implicit output

AdmBorkBork

Posted 2016-12-05T19:37:45.340

Reputation: 41 581

2

T-SQL, 202 Bytes

DECLARE @b varchar(max)='1',@ int=1 declare @l int=LEN(@b)declare @o bigint=CAST(SUBSTRING(@b,@l,1)AS bigint)WHILE @<@l BEGIN SET @o=@o+POWER(CAST(SUBSTRING(@b,@l-@,1)*2AS bigint),@)SET @=@+1 END PRINT @o

Nelz

Posted 2016-12-05T19:37:45.340

Reputation: 321

2

PHP, 64 bytes

foreach(str_split(strrev($argv[1]))as$k=>$v)$t+=$v*2**$k;echo$t;

We reverse our binary number, split it into its component digits, and sum them based on position.

Xanderhall

Posted 2016-12-05T19:37:45.340

Reputation: 1 236

2

Bash + GNU utilities, 29 bytes

sed 's/./2*&+/g;s/.*/K&p/'|dc

I/O via stdin/stdout.

The sed expression splits the binary up into each digit and builds a RPN expression for dc to evaluate.

Digital Trauma

Posted 2016-12-05T19:37:45.340

Reputation: 64 644

2

Clojure, 114 105 63 41 bytes

V4: 41 bytes

-22 bytes thanks to @cliffroot. Since digit is a character, it can be converted to it's code via int, then have 48 subtracted from it to get the actual number. The map was also factored out. I don't know why it seemed necessary.

#(reduce(fn[a d](+(* a 2)(-(int d)48)))%)

V3: 63 bytes

(fn[s](reduce #(+(* %1 2)%2)(map #(Integer/parseInt(str %))s)))

-42 bytes (!) by peeking at other answers. My "zipping" was evidently very naïve. Instead of raising 2 to the current place's power, then multiplying it by the current digit and adding the result to the accumulator, it just multiplies the accumulator by 2, adds on the current digit, then adds it to the accumulator. Also converted the reducing function to a macro to shave off a bit.

Thanks to @nimi, and @Adnan!

Ungolfed:

(defn to-dec [binary-str]
  (reduce (fn [acc digit]
            (+ (* acc 2) digit))
          (map #(Integer/parseInt (str %)) binary-str)))

V2: 105 bytes

#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range)(reverse %)))

-9 bytes by reversing the string so I don't need to create an awkward descending range.

V1: 114 bytes

Well, I'm certainly not winning! In my defense, this is the first program I've ever written that converts between bases, so I had to learn how to do it. It also doesn't help that Math/pow returns a double that requires converting from, and Integer/parseInt doesn't accept a character, so the digit needs to be wrapped prior to passing.

#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range(dec(count %))-1 -1)%))

Zips the string with a descending index representing the place number. Reduces over the resulting list.

Ungolfed:

(defn to-dec [binary-str]
  (reduce (fn [acc [place digit]]
            (let [parsed-digit (Integer/parseInt (str digit))
                  place-value (long (Math/pow 2 place))]
              (+ acc (* parsed-digit place-value))))
          0
          (map vector (range (dec (count binary-str)) -1 -1) binary-str)))

Carcigenicate

Posted 2016-12-05T19:37:45.340

Reputation: 3 295

#(reduce(fn[a b](+(* a 2)(-(int b)48)))0 %) improved version. Moved map part of code directly into reduce, changed integer parsing method, make external function with shorthand lambda syntax. – cliffroot – 2016-12-06T14:46:30.510

@cliffroot int can be used to parse!? That'll knock off like 10 bytes in every challenge I've done here lol. – Carcigenicate – 2016-12-06T18:40:07.587

Oh, I see what you're doing. Taking the ascii code, then subtracting to get the value. I guess this would only work in select circumstances only. Oh well, thanks for the tip. – Carcigenicate – 2016-12-06T18:42:37.967

2

Mathematica, 27 13 11 bytes

Fold[#+##&]

Accepts a List of bits as input (e.g. {1, 0, 1, 1, 0} -- Mathematica's binary representation of the number 22)

JungHwan Min

Posted 2016-12-05T19:37:45.340

Reputation: 13 290

Following up from the comment on Greg's answer, how is "splitting all the digits in the input" not a base conversion function? – Martin Ender – 2016-12-06T05:33:31.683

@MartinEnder I'm using it like the Characters function. – JungHwan Min – 2016-12-06T05:48:06.153

@MartinEnder Actually, as seen in @nimi's answer, I could just accept a list of 1s and 0s because that is the only way to represent a binary number in Mathematica, meaning I don't need IntegerDigits in the first place.

– JungHwan Min – 2016-12-06T05:52:27.093

That assumes that base 10 is the "natural" representation of an integer. An actual integer value has no preferred base attached to it (I guess you could say the way it's stored is probably base 256 or maybe even base 2 but that's an implementation detail). Just because we (normally) use base 10 to write integer literals there doesn't mean integer values are already in base 10. – Martin Ender – 2016-12-06T05:52:41.343

@MartinEnder @Lynn's Jelly code uses D, which does the same thing as IntegerDigits

– JungHwan Min – 2016-12-06T05:53:32.423

well then I think that's invalid too. I guess I'll ask the OP. – Martin Ender – 2016-12-06T05:55:06.877

Actually, Dennis already did. – Martin Ender – 2016-12-06T05:55:42.387

http://codegolf.stackexchange.com/questions/102219/binary-to-decimal-converter/102223#comment248521_102223 (discussion on digit extraction built-ins is still happening) – Martin Ender – 2016-12-06T10:06:51.913

So the result of the discussion was that IntegerDigits is valid but taking list input isn't. – Martin Ender – 2016-12-07T20:48:52.427

2

JavaScript (ES6), 32 bytes

f=([...n])=>n+n&&+n.pop()+2*f(n)

Recursion saves the day again! Though the parameterization seems a little long...

ETHproductions

Posted 2016-12-05T19:37:45.340

Reputation: 47 880

Since it's a single "argument", does [...n] need to be surrounded in parentheses? – Cyoce – 2016-12-11T18:38:26.953

@Cyoce Unfortunately, yes, or JS throws a SyntaxError. – ETHproductions – 2016-12-11T21:18:02.677

2

R (32-bit), 64 Bytes

Input for the function should be given as character. The base functions of R support 32-bit integers.

Input:

# 32-bit version (base)
f=function(x)sum(as.double(el(strsplit(x,"")))*2^(nchar(x):1-1))
f("1")
f("10")
f("101010")
f("1101111111010101100101110111001110001000110100110011100000111")

Output:

> f("1")
[1] 1
> f("10")
[1] 2
> f("101010")
[1] 42
> f("1101111111010101100101110111001110001000110100110011100000111")
[1] 2.016121e+18

R (64-bit), 74 Bytes

Input for the function should be given as character. The package bit64 has to be used for 64-bit integers.

Input:

# 64-bit version (bit64)
g=function(x)sum(bit64::as.integer64(el(strsplit(x,"")))*2^(nchar(x):1-1))
g("1")
g("10")
g("101010")
g("1101111111010101100101110111001110001000110100110011100000111")

Output:

> g("1")
integer64
[1] 1
> g("10")
integer64
[1] 2
> g("101010")
integer64
[1] 42
> g("1101111111010101100101110111001110001000110100110011100000111")
integer64
[1] 2016120520371234567

djhurio

Posted 2016-12-05T19:37:45.340

Reputation: 1 113

2You can do: el(strsplit(x,"")) instead of strsplit(x,split="")[[1]] to save a couple of bytes. – Billywob – 2016-12-07T10:14:25.600

Thanks a lot! Especially for the el function - I was not aware of it. – djhurio – 2016-12-07T20:47:35.290

2

Perl, 21 19 16 + 4 = 20 bytes

-4 bytes thanks to @Dada

Run with -F -p (including the extra space after the F). Pipe values to the function using echo -n

$\+=$_+$\for@F}{

Run as echo -n "101010" | perl -F -pE '$\+=$_+$\for@F}{'

I feel this is sufficiently different from @Dada's answer that it merits its own entry.

Explanation:

-F                              #Splits the input character by character into the @F array
-p                              #Wraps the entire program in while(<>){ ... print} turning it into
while(<>){$\+=$_+$\for@F}{print}
                   for@F        #Loops through the @F array in order ($_ as alias), and...
          $\+=$_+$\             #...doubles $\, and then adds $_ to it (0 or 1)...
while(<>){              }       #...as long as there is input.
                         {print}#Prints the contents of $_ (empty outside of its scope), followed by the output record separator $\

This uses my personal algorithm of choice for binary-to-decimal conversion. Given a binary number, start your accumulator at 0, and go through its bits one by one. Double the accumulator each bit, then add the bit itself to your accumulator, and you end up with the decimal value. It works because each bit ends up being doubled the appropriate number of times for its position based on how many more bits are left in the original binary number.

Gabriel Benamy

Posted 2016-12-05T19:37:45.340

Reputation: 2 827

Even shorter : perl -F -pE '$\+=$_+$\for@F}{' – Dada – 2016-12-06T19:51:24.313

I honestly laughed at how short this is now. Thank you. – Gabriel Benamy – 2016-12-06T19:56:29.573

Yea, it's pretty neat, well done! – Dada – 2016-12-06T20:04:20.487

2

Dyalog APL, 12 bytes

(++⊢)/⌽⍎¨⍞

get string input

⍎¨ convert each character to number

reverse

(...)/ insert the following function between the numbers

++⊢ the sum of the arguments plus the right argument


ngn shaved 2 bytes.

Adám

Posted 2016-12-05T19:37:45.340

Reputation: 37 779

1

k, 8 bytes

Same method as the Haskell answer above.

{y+2*x}/

Example:

{y+2*x}/1101111111010101100101110111001110001000110100110011100000111b
2016120520371234567

skeevey

Posted 2016-12-05T19:37:45.340

Reputation: 4 139

1

Java 7, 87 bytes

long c(String b){int a=b.length()-1;return a<0?0:b.charAt(a)-48+2*c(b.substring(0,a));}

For some reason I always go straight to recursion. Looks like an iterative solution works a bit nicer in this case...

Poke

Posted 2016-12-05T19:37:45.340

Reputation: 3 075

1

JavaScript (ES7), 56 47 bytes

Reverses a binary string, then adds each digit's value to the sum.

n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)

Demo

f=n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
document.write( f('101010') ) // 42

darrylyeo

Posted 2016-12-05T19:37:45.340

Reputation: 6 214

1

MATL, 8, 7 bytes

"@oovsE

Try it online!

One byte saved thanks to @LuisMendo!

Alternate approach: (9 bytes)

ootn:PW*s

James

Posted 2016-12-05T19:37:45.340

Reputation: 54 537

1

JavaScript, 18 83 bytes

f=n=>parseInt(n,2)

f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)

Demo

f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)
document.write(f('1011')) // 11

Oliver

Posted 2016-12-05T19:37:45.340

Reputation: 7 160

Uses a built-in, which is disallowed. – Yytsi – 2016-12-05T21:41:28.883

@TuukkaX Ah, missed that. Thanks. – Oliver – 2016-12-05T21:42:04.333

1I was just about to do the same thing (in c#), I'm bad at reading. – Yodle – 2016-12-05T21:42:32.230

It's a code golf challenge, try to write short code. (y==='1') could be +y – edc65 – 2016-12-05T22:01:58.457

1

JavaScript (ES6), 38

Simple is better

s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")

Test

f=s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")

console.log("Test 0 to 99999")
for(e=n=0;n<100000;n++)
{  
  b=n.toString(2)
  r=f(b)
  if(r!=n)console.log(++e,n,b,r)
}
console.log(e+" errors")

  

edc65

Posted 2016-12-05T19:37:45.340

Reputation: 31 086

1

Turing Machine Code, 272 bytes

(Using, as usual, the morphett.info rule table syntax)

0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 1 l 1
1 1 0 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 0 l 3
4 * * r 4
4 _ _ r A

AKA "Yet another trivial modification of my earlier base converter programs."

Try it online, or you can also use test it using this java implementation.

SuperJedi224

Posted 2016-12-05T19:37:45.340

Reputation: 11 342

1

MATL, 7 bytes

PoofqWs

Try it online!

P   % Implicitly input string. Reverse
o   % Convert to array of ASCII codes
o   % Modulo 2: '1' becomes 1, '0' becomes 0
f   % Find: push array of 1-based indices of nonzeros
q   % Subtract 1 from each entry
W   % 2 raised to each entry
s   % Sum of array. Implicitly display

Luis Mendo

Posted 2016-12-05T19:37:45.340

Reputation: 87 464

2My mind went Poof! – Adám – 2016-12-12T14:54:28.087

1

Befunge, 20 18 bytes

Input must be terminated with EOF rather than EOL (this lets us save a couple of bytes)

>+~:0`v
^*2\%2_$.@

Try it online!

Explanation

>             The stack is initially empty, the equivalent of all zeros.
 +            So the first pass add just leaves zero as the current total. 
  ~           Read a character from stdin to the top of the stack.
   :0`        Test if greater than 0 (i.e. not EOF)
      _       If true (i.e > 0) go left.
    %2        Modulo 2 is a shortcut for converting the character to a numeric value.
   \          Swap to bring the current total to the top of the stack.
 *2           Multiply the total by 2.
^             Return to the beginning of the loop,
 +            This time around add the new digit to the total.

                ...on EOF we go right...
       $      Drop the EOF character from the stack.
        .     Output the calculated total.
         @    Exit.

James Holderness

Posted 2016-12-05T19:37:45.340

Reputation: 8 298

I had like a 60-something byte code that was dealing with integers, and wow, this is so much more simple and elegant. Great job, and nice explanation too. – MildlyMilquetoast – 2016-12-06T05:14:57.823

1

Ruby, 37 bytes

ruby -e 'o=0;gets.each_byte{|i|o+=o+i%2};p o/2'
         1234567890123456789012345678901234567

This depends on the terminating \n (ASCII decimal 10) being zero modulo 2 (and on ASCII 0 and 1 being 0 and 1 mod two, respectively, which thankfully they are).

DepressedDaniel

Posted 2016-12-05T19:37:45.340

Reputation: 311

1

아희(Aheui), 40 bytes

아빟뱐썩러숙
뎌반뗘희멍파퍄

Accepts a string composed of 1s and 0s.

To try online

Since the online Aheui interpreter does not allow arbitrary-length strings as inputs, this alternative code must be used (identical code with slight modifications):

Add the character at the end of the first line (after ) length(n)-times.

어우
우어
뱐썩러숙
번댜펴퍼망희땨

If the input is 10110, the first line would be 어우벟벟벟벟벟.

When prompted for an input, do NOT type quotation marks. (i.e. type 10110, not "10110")

Try it here! (copy and paste the code)

JungHwan Min

Posted 2016-12-05T19:37:45.340

Reputation: 13 290

1

ClojureScript, 36 bytes

(fn[x](reduce #(+(* 2 %)(int %2))x))

or

#(reduce(fn[a n](+(* 2 a)(int n)))%)

The straightforward reduction. Takes a string as input.

MattPutnam

Posted 2016-12-05T19:37:45.340

Reputation: 521

1

Minkolang v0.15, 23 19 bytes

n6ZrI[2%2i;*1R]$+N.

Try it online!

Explanation

n                             gets input in the form of a number
 6Z                           converts to string (so that it is split into an array)
   r                          reverses it
    I                         gets the stack length
     [        ]               for loop with the stack's length as the number of iterations
      2%                       gets the modulo of the ascii value
                               1 =(string conversion)> 49 =(after modulo)> 1
                               0 =(string conversion)> 48 =(after modulo)> 0
        2i;                    raises 2 to the power of the loop counter
           *                   multiplies it by the modulo
            1R                 rotates stack 1 time
              $+              sums everything
                N.            outputs as number and exit

user41805

Posted 2016-12-05T19:37:45.340

Reputation: 16 320

1

Common Lisp, 99 88 72 bytes

Takes a string as input

(defun f(s)(reduce(lambda(a d)(+ d(* a 2)))(map'list #'digit-char-p s)))

Ungolfed:

(defun bin-to-dec (bin-str)
  (reduce (lambda (acc digit) (+ digit (* acc 2)))
          (map 'list #'digit-char-p bin-str)))

Bart van Nierop

Posted 2016-12-05T19:37:45.340

Reputation: 131

1

><> (Fish) 36 28 bytes

/i:1+?!v$2*$2%+!| !
/0| ;n~<

Edit 1: Forgot to put the output in the original. Added output and used MOD 2 instead of minus 48 to convert ascii to decimal to save the extra bytes lost. (no change in bytes)

Edit 2: Changed the algorithm completely. Each loop now does this; times current value by 2, then add the mod of the input. (saving of 8 bytes)

Online version

Try it Online! - This works with bigger numbers than the above link.

Teal pelican

Posted 2016-12-05T19:37:45.340

Reputation: 1 338

1

C, 44 bytes

d(s,v)char*s;{return*s?d(s,v+=v+*s++-48):v;}

Use as follows :

int main(){
  printf("%i\n", d("101010",0));
}

Remove two bytes and an unused parameter thanks to Steadybox

Charles Paulet

Posted 2016-12-05T19:37:45.340

Reputation: 51

You have an unused parameter c there. Removing it saves two bytes. – Steadybox – 2016-12-06T19:49:22.197

1

Haskell, 31 bytes

f=foldl(\a b->2*a+(read$b:[]))0

Takes input in string format (e.g. "1111"). Produces output in integer format (e.g. 15).

:[] Converts from an element to an array -- in this chase from Char to [Char] (String). read Converts from string to whatever context it's in (in this case the context is addition, so converts to Num)

so (read$b:[]) converts b from Char to Num. a is the accumulator, so multiply that by two and add the Num version of b.

If input in the format [1,1,1,1] was allowed, the 18 byte

f=foldl((+).(2*))0

would work, but since it's not, it doesn't.

Joshua David

Posted 2016-12-05T19:37:45.340

Reputation: 211

1

C, 41 37 bytes

i;b(char*s){i+=i+*s++%2;i=*s?b(s):i;}

Wandbox

o79y

Posted 2016-12-05T19:37:45.340

Reputation: 509

1

MATLAB, 49 bytes

@(a)dot(int2str(a)-'0',2.^(floor(log10(a)):-1:0))

Anonymous function that splits the input into an array with int2str(a)-'0', then does a dot product with powers of 2. Has rounding error for the last test case, will update the solution when I figure out a fix.

MattWH

Posted 2016-12-05T19:37:45.340

Reputation: 331

1

Forth (gforth 0.7.3), 47 bytes

: x 2 base ! bl parse s>number drop decimal . ;

: x - define new word with name 'x'
2 base ! - set base to binary
bl parse - read line until a space (bl) or EOL
s>number - try to convert the string to number
drop - we only want the converted number and not the success flag
decimal - set base to decimal
. - print value on top of stack
; - end of definition

Test cases:

x 1 1  ok
x 10 2  ok
x 101010 42  ok
x 1101111111010101100101110111001110001000110100110011100000111 2016120520371234567  ok

2xsaiko

Posted 2016-12-05T19:37:45.340

Reputation: 699

Sorry, forget my last comment, I thought this answer was to another challenge :/ The answer is perfectly valid :) – Stewie Griffin – 2016-12-23T12:09:40.750

0

Pyke, 10 9 bytes

1QY_%0m@s

Try it here!

 QY_      -    reverse digits input
1   %     -   get indecies with a value of 1
     0m@  -  map(set_nth_bit(0, i), ^)
        s - sum(^)

Also 9 bytes

Y_'XltV}+

Try it here!

Y_        - reverse digits
  'Xlt    - splat(^), len(^)-1
      V   - repeat length times:
       }+ -  double and add to stack

Blue

Posted 2016-12-05T19:37:45.340

Reputation: 26 661

0

Jelly, 10 bytes

DLḶ2*U,DPS

You know your Jelly code is still golfable when it's above 7 bytes...

It basically consists of two parts
   2*       generate a list of the powers of two
 LḶ         for all the powers of 2 from 0 to the length of the binary input
D           Convert the binary string into a list to get its length with L   
     U      Then upend that list (for '101010', we now have a list of [32, 16, 8, 4, 2, 1]
      ,     Combine this list
       D    with the individual digits of the input  
        P   multiply them with eah other [32*1, 16*0, 8*1, 4*0, 2*1, 1*0]
         S  And sum the result      42 =   32 +  0  +  8 +  0 +  2 +  0

Try it online!

steenbergh

Posted 2016-12-05T19:37:45.340

Reputation: 7 772

0

Mathematica, 44 bytes

2^Range[Length[d=IntegerDigits@#]-1,0,-1].d&

Unnamed function taking an integer argument (interpreted as a base-10 integer, but will only have the digits 0 and 1) and returning an integer. d is set equal to the set of digits, and then the dot product of d with the appropriate sequence of powers of 2 generates the value.

Greg Martin

Posted 2016-12-05T19:37:45.340

Reputation: 13 940

1"You are not allowed to use any builtin base conversion functions." I'd consider IntegerDigits one of those. – Martin Ender – 2016-12-05T22:29:58.770

@MartinEnder I think he's using IntegerDigits just to split all the digits in the input. The conversion part is done by 2^Range[...].d – JungHwan Min – 2016-12-05T23:54:24.210

In any case, JHM's answer is way better than mine :) so let's contemplate the use of IntegerDigits over there. If it's disallowed, JHM and I will presumably use the same string-based preprocessing step, and the other answer will still be better! – Greg Martin – 2016-12-06T00:14:26.177

0

JavaScript, 35 bytes

f=([c,...b],n=0)=>c<2?f(b,+c+n+n):n

For c='1' and c='0', c<2 returns true.
If b is empty, c will be undefined in the next recursion and c<2 will be false.

Titus

Posted 2016-12-05T19:37:45.340

Reputation: 13 814

Hehe ... the 35th answer has 35 bytes. :) – Titus – 2016-12-05T23:14:15.520

0

Julia 0.5, 22 bytes

!n=n>0&&2*!(n÷10)|n&1

Try it online!

Dennis

Posted 2016-12-05T19:37:45.340

Reputation: 196 637

0

SmileBASIC, 47 44 bytes

INPUT B$WHILE""<B$N=N*2+VAL(SHIFT(B$))WEND?N

Another program of the same size:

INPUT B$WHILE""<B$N=N*2OR"0"<SHIFT(B$)WEND?N

12Me21

Posted 2016-12-05T19:37:45.340

Reputation: 6 110