In how many bits do I fit

52

2

For any positive 32-bit integer (1 ≤ n ≤ 0xFFFFFFFF) output the number of bits needed to represent that integer.

Test cases

| n    | n in binary | bits needed |
|----------------------------------|
| 1    | 1           | 1           |
| 2    | 10          | 2           |
| 3    | 11          | 2           |
| 4    | 100         | 3           |
| 7    | 111         | 3           |
| 8    | 1000        | 4           |
| 15   | 1111        | 4           |
| 16   | 10000       | 5           |
| 128  | 10000000    | 8           |
| 341  | 101010101   | 9           |

4294967295 => 11111111111111111111111111111111 => 32

So f(16) would print or return 5

This is . Shortest code in bytes wins

Bassdrop Cumberwubwubwub

Posted 2016-12-27T16:05:05.810

Reputation: 5 707

2This is the ceiling of the base-2 logarithm. – orlp – 2016-12-27T16:51:22.520

23@orlp It actually is floor(log2(num))+1 – user41805 – 2016-12-27T16:52:37.757

2@KritixiLithos Right. – orlp – 2016-12-27T18:46:30.903

@KritixiLithos What's an example for when ceil(log2(num)) != floor(log2(num)) + 1? I'm racking my brain trying to figure out why the distinction is important. – Brian J – 2016-12-27T20:21:38.563

3Nevermind, just realized that the distinct is important when num is a power of two. – Brian J – 2016-12-27T20:22:47.377

11

This is a trivial challenge with a lot of trivial solutions. There are however some non-trivial solutions too. To voters: Please read the first sentence of this meta post before upvoting builtin functions. (humbly taken from this comment)

– user41805 – 2016-12-28T08:23:53.787

Am I wrong that you need 32 bits to represent any 32-bit integer? If I want to represent 1 in binary, I need 31 0's and one 1. I can't store "11" as "11" in memory. – MatthewRock – 2016-12-29T13:23:47.867

@MatthewRock Technically, you could store 1 in one bit (1). With fixed-width integers, yes, that would take up 32 bits (assuming 32-bit word size), but 31 of those bits are redundant (leading zeroes). – Mego – 2016-12-30T23:23:01.580

Just out of curiosity, how many bits does it take to store zero (0)? – Octopus – 2017-01-20T23:17:04.387

@Octopus 1 bit. – Bassdrop Cumberwubwubwub – 2017-02-08T13:10:36.257

@BrianJ But this: ceil(log2(num+1)) == floor(log2(num)) + 1 – ბიმო – 2017-07-19T17:04:24.407

For 64 bit (without the +1). – user202729 – 2018-12-10T13:31:28.553

Answers

30

05AB1E, 2 bytes

bg

Try it online!

Magic Octopus Urn

Posted 2016-12-27T16:05:05.810

Reputation: 19 422

16Esoteric language won again... bg – devRicher – 2016-12-27T16:06:21.657

20@devRicher I expect to be beaten by a 1 byte solution still, to be honest. – Magic Octopus Urn – 2016-12-27T16:08:13.207

9At least this answer gets it's upvotes; it's not in the bg. – NoOneIsHere – 2016-12-27T21:59:43.743

3bg in gaming means bad game :) – YoYoYonnY – 2016-12-31T21:10:03.037

1@yoyoyonny or battleground haha. – Magic Octopus Urn – 2017-01-02T17:37:59.293

Or (and I may be dating myself a little) Blood-Gulch (halo 3) lol. – Magic Octopus Urn – 2018-05-15T12:22:43.290

35

JavaScript (ES6), 18 bytes

f=n=>n&&1+f(n>>>1)
<input type=number min=0 step=1 value=8 oninput="O.value=f(this.value)">
<input id=O value=4 disabled>

ETHproductions

Posted 2016-12-27T16:05:05.810

Reputation: 47 880

This is one of the few non-trivial solution here. Nice tactic! – user41805 – 2016-12-27T19:01:04.480

1Should it be n>>>1 to support n > 0x7FFFFFFF? – Arnauld – 2016-12-27T22:56:39.240

@Arnauld Hmm, didn't know >> failed on n that high. Thanks. – ETHproductions – 2016-12-28T00:41:55.643

Nice, my first attempt was f=(a,b=1)=>a>1?f(a>>1,++b):b – Bassdrop Cumberwubwubwub – 2016-12-28T09:58:42.430

28

x86 Assembly, 4 bytes

Assuming Constant in EBX:

bsr eax,ebx
inc eax

EAX contains the number of bits necessary for Constant.

Bytes: ☼¢├@

Hexadecimal: ['0xf', '0xbd', '0xc3', '0x40']

z0rberg's

Posted 2016-12-27T16:05:05.810

Reputation: 409

2Could you please include a hexdump of the actual 8 byte compiled x86 Assembly code? – Loovjo – 2016-12-27T19:37:38.893

Did so. And thank you, because I realized I made a mistake. I added an "inc eax" to fit the rules. I lost a byte. :( – z0rberg's – 2016-12-27T19:58:56.260

Oh wow you changed my post to proper formatting. Thanks for correcting it! – z0rberg's – 2016-12-27T20:03:47.993

2

By the way, Assembly submissions can assume that the input is already stored in a specific register, so I think you could shave off a few bytes that way.

– Loovjo – 2016-12-27T20:03:50.317

Oh that's nice! Well, then it's down to four! – z0rberg's – 2016-12-27T20:06:18.910

1Is it customary to count assembly submissions as the number of bytes of the compiled machine code rather than the assembly language source code? – smls – 2017-01-17T18:17:35.313

18

Python, 14 bytes

int.bit_length

Try it online!

Dennis

Posted 2016-12-27T16:05:05.810

Reputation: 196 637

It works in Python 2, too. – vaultah – 2016-12-27T16:13:55.140

1It does indeed. Forgot Python 2‘s int was 64 bits wide, not 32 bits. – Dennis – 2016-12-27T16:17:39.963

Python 3's bit_length is bit_length(). – dfernan – 2016-12-28T19:36:37.110

2@dfernan This is not a function call; it's a function. If n is an int, int.bit_length(n) and n.bit_length() do exactly the same. – Dennis – 2016-12-28T19:43:19.543

@Dennis, understood. In that case, your answer is not entirely correct and should depict an additional three bytes. – dfernan – 2016-12-29T10:34:38.040

@dfernan I'm sorry, but I don't understand which three bytes you're talking about. – Dennis – 2016-12-29T10:51:36.997

I was referring to (n) from int.bit_length(n), as int.bit_length by its own is not valid, working code. – dfernan – 2016-12-29T10:53:36.327

2

@dfernan int.bit_length(n) is a function call, and thus a snippet that assumes the input is stored in a variable. This is not allowed by our rules, so appending (n) would make this answer invalid. However, int.bit_length evaluates to a function and can be saved in a variable for later use. This is allowed by default.

– Dennis – 2016-12-29T10:57:58.043

@Dennis, thanks for the explanation. – dfernan – 2016-12-29T11:07:10.217

n.bit_length() is the way it would be used in the code e.g., 123 .bit_length(). If the assembly solution may assume that the input is in a registry then Python solution should be allowed to get the input from a variable too. Though if the question is to write a function then int.bit_length works too (f= is implied and Class.method(instance) is allowed in Python in addition to instance.method()). – jfs – 2016-12-29T15:00:55.780

@J.F.Sebastian I see your point, but Assembly programs may take input from registers is an I/O rule that doesn't apply to all languages.

– Dennis – 2016-12-29T15:04:34.073

@J.F.Sebastian The comments of some random answer isn't the place to debate the rules that have been set down. If you disagree with the popular rulings, post your own answer on the relevant meta question, with clearly explained reasoning, including how you think it'll make things better (which, incidentally, can't just be "makes golfing easier"). If people agree (i.e. upvote), then bam! Rules changed. That can't happen if you just discuss it in comments. – Fund Monica's Lawsuit – 2016-12-30T06:09:43.020

15

Labyrinth, 13 12 bytes

 ?
_:
2/#(!@

Try it online!

Explanation

The program simply repeatedly divides the input by 2 until it's zero. The number of steps are kept track of by duplicating the value at each step. Once it's reduced to zero we print the stack depth (minus 1).

The program starts at the ? which reads the input. The main loop is then the 2x2 block below, going counter-clockwise:

:   Duplicate current value.
_2  Push 2.
/   Divide.

Once the value is zero after a full iteration, the linear bit at the end is executed:

#   Push stack depth.
(   Decrement.
!   Print.
@   Terminate.

Martin Ender

Posted 2016-12-27T16:05:05.810

Reputation: 184 808

5This solution is complete - it takes input and provides the answer, and does not utilise any existing function for this specific purpose - it calculates the answer manually. To me this is more in the spirit of the game than most other answers. – Johan – 2016-12-27T20:39:12.830

15

C, 31 bytes

f(long n){return n?1+f(n/2):0;}

... Then I thought about recursion. From obscure to obvious, and with one fourth of the length dropped off.

See it live on Coliru


C, 43 bytes

c;
#define f(v)({for(c=0;v>=1l<<c;++c);c;})

Calling f with an unsigned value (e.g. f(42u)) will "return" its bit length. Even works for 0u !

Ungolfed and explained: (backslashes omitted)

c;
#define f(v)
    ({ // GCC statement-expression

        // Increment c until (1 << c) >= v, i.e
        // that's enough bits to contain v.
        // Note the `l` to force long
        // arithmetic that won't overflow.
        for(c = 0; v >= 1l << c; ++c)
            ; // Empty for body

        c; // Return value
    })

See it live on Coliru

Quentin

Posted 2016-12-27T16:05:05.810

Reputation: 1 187

OP guarantees n>=1, so n?...:0 is not necessary. – Mad Physicist – 2016-12-29T21:55:42.487

1@MadPhysicist well I do have to stop the recursion somewhere, don't I ;) – Quentin – 2016-12-29T21:56:58.860

OIC. Didn't read carefully, feel like a dumbass now. Neat answer either way. – Mad Physicist – 2016-12-29T21:59:41.217

@MadPhysicist no worries, thank you very much :) – Quentin – 2016-12-29T22:03:17.673

For the non-recursive solution assuming gcc statement expressions, I reckon you might have been inclined to use the #define f(n) ({64-__builtin_clzl(n);}) approach as well. – Moreaki – 2017-01-01T13:10:02.060

@Moreaki yep. For some reason I was sure that the builtin would be too long -- but now Digital Trauma has pretty much nailed it that way.

– Quentin – 2017-01-01T13:30:54.367

14

Mathematica, 9 bytes

BitLength

Alternatively:

Floor@Log2@#+1&
#~IntegerLength~2&

Martin Ender

Posted 2016-12-27T16:05:05.810

Reputation: 184 808

14

Perl 6, 7 bytes

*.msb+1

Try it

Explanation:

* makes it become a WhateverCode lambda, and indicates where to put the input

.msb on an Int returns the index of the most significant bit (0 based)

+1 is combined into the lambda, and adds one to the eventual result of calling .msb.

Brad Gilbert b2gills

Posted 2016-12-27T16:05:05.810

Reputation: 12 713

13

C preprocessor macro (with gcc extensions), 26

#define f 32-__builtin_clz

Uses GCC's count-leading-zeros builtin.

Call this as a function, e.g. f(100).

Try it online.

Digital Trauma

Posted 2016-12-27T16:05:05.810

Reputation: 64 644

Oh wow, I thought about using a builtin but dropped the idea because I thought it was going to be too long... Well played. – Quentin – 2016-12-28T08:55:36.903

Lucky the OP specified n >= 1 :D – Matthieu M. – 2017-01-02T14:04:02.013

12

Retina, 56 37 bytes

This solution works with all the required input values.

The biggest problem Retina faces in this challenge is the fact that its strings have a maximum length of 2^30 characters, so the usual way of dealing with numbers (unary representation) doesn't work with values greater than 2^30.

In order to solve this problem I adopted a different approach, keeping a sort of decimal representation of numbers, but where each digit is written in unary (I'll call this representation digitunary). For example the number 341 would be written as 111#1111#1# in digitunary. With this representation we can now work with numbers of up to 2^30/10 digits (~ a hundred million digits). It is less practical than standard unary for arbitrary arithmetic, but with a bit of effort we could do any kind of operations.

NOTE: digitunary in theory could use any other base (e.g. binary 110 would be 1#1## in base 2 digitunary), but since Retina has builtins to convert between decimal and unary and no direct way to deal with other bases, decimal is probably the most manageable base.

The algorithm I used is making successive integer divisions by two until we reach zero, the number of divisions we made is the number of bits needed to represent this number.

So, how do we divide by two in digitunary? Here's the Retina snippet that does it:

(1*)(1?)\1#        We divide one digit, the first group captures the result, the second group captures the remainder
$1#$2$2$2$2$2      The result is put in place of the old number, the remainder passes to the next digit (so it is multiplied by 10) and is divided by two there -> 5 times the remainder goes to the next digit

This replacement is enough to divide a digitunary number by 2, we just need to remove possible .5s from the end if the original number was odd.

So, here's the full code, we keep dividing by two until there are still digits in the number, and put a literal n in front of the string at each iteration: the number of n at the end is the result.

.                  |
$*1#               Convert to digitunary
{`^(.*1)           Loop:|
n$1                    add an 'n'
(1*)(1?)\1#            |
$1#$2$2$2$2$2          divide by 2
)`#1*$                 |
#                      erase leftovers
n                  Return the number of 'n's in the string

Try it online!


Updated solution, 37 bytes

Big refactoring with many good ideas that golfed about a third of the length, all thanks to Martin Ender!

The main idea is to use _ as our unary symbol: in this way we can use regular digits in our string, as long as we convert them back to _s when it is needed: this lets us save many bytes on division and on insertion of multiple digits.

Here's the code:

<empty line>    |
#               put a # before each digit and at the end of the string 
{`\d            Loop:|
$*_                 Replace each digit with the corrisponding number of _
1`_                 |
n_                  Add an 'n' before the first _
__                  |
1                   Division by 2 (two _s become a 1)
_#                  |
#5                  Wherever there is a remainder, add 5 to the next digit
}`5$                |
                    Remove the final 5 you get when you divide odd numbers
n               Return the number of 'n's in the string

Try it online!

Leo

Posted 2016-12-27T16:05:05.810

Reputation: 8 482

1I've used a similar numeric form (but called it Unary-Coded Decimal), which is pretty handy for arithmetic with Sed. – Toby Speight – 2018-05-15T15:02:40.693

11

Ruby, 19 16 bytes

->n{"%b"%n=~/$/}

Thanks Jordan for golfing off 3 bytes

Alexis Andersen

Posted 2016-12-27T16:05:05.810

Reputation: 591

You can save a byte with %: ->n{("%b"%n).size}. – Jordan – 2016-12-28T06:49:06.707

3Wait, this is shorter: ->n{"%b"%n=~/$/}. – Jordan – 2016-12-28T06:51:08.210

10

JavaScript ES6, 19 bytes

a=>32-Math.clz32(a)

Math.clz32 returns the number of leading zero bits in the 32-bit binary representation of a number. So to get the amount of bits needed, all we need to do is substract that number from 32

f=
  a=>32-Math.clz32(a)
  
pre {
    display: inline;
}
<input id=x type="number" oninput="y.innerHTML = f(x.value)" value=128><br>
<pre>Bits needed: <pre id=y>8</pre></pre>

Bassdrop Cumberwubwubwub

Posted 2016-12-27T16:05:05.810

Reputation: 5 707

2The alternative a=>1+Math.log2(a)|0 is also 19 bytes. – Neil – 2016-12-27T18:24:32.790

5@Neil 1+...|0 screams minus tilde! a=>-~Math.log2(a) is 18 – edc65 – 2016-12-28T12:37:57.620

@edc65 I count 17... but yes, I was sure I was missing something, thanks for pointing it out. – Neil – 2016-12-28T17:10:27.567

@Neil Feel free to post it as a seperate answer. It uses a different method than my answer so it would feel unfair to use yours for a reduced byte count – Bassdrop Cumberwubwubwub – 2016-12-29T10:10:45.800

10

Jolf, 2 bytes

lB

Just convert to binary and then find the length.

Rɪᴋᴇʀ

Posted 2016-12-27T16:05:05.810

Reputation: 7 410

10

Julia 0.4, 14 bytes

!n=log2(2n)÷1

Try it online!

Dennis

Posted 2016-12-27T16:05:05.810

Reputation: 196 637

2Much more interesting than the other answers. +1 – Magic Octopus Urn – 2016-12-27T17:20:34.793

10

bash / Unix tools, 16 bytes

dc<<<2o$1n|wc -c

Save this in a script, and pass the input as an argument. The number of bits required to represent that number in binary will be printed.

Here's an explanation:

dc is a stack-based calculator. Its input, parsed into tokens, is:

2 — Push 2 on the stack.

o — Pop a value off the stack (which is 2) and make it the output base (so output is now in binary).

The value of the argument to the bash program ($1) — Push that argument on the stack.

n — Pop a value off the stack (which is the input number) and print it (in binary, because that's the output base) with no trailing newline.

So the dc command prints the number in binary.

The output of dc is piped to the command wc with the -c option, which prints the number of characters in its input.

The end result is to print the number of digits in the binary representation of the argument.

Mitchell Spector

Posted 2016-12-27T16:05:05.810

Reputation: 3 392

Nice choice of language, but it would be even cooler if you included an explanation. – NH. – 2016-12-31T13:37:53.173

@NH Thanks. I've added an explanation. – Mitchell Spector – 2016-12-31T18:37:33.150

9

Google Sheets, 15 Bytes

Takes input from cell A1 and outputs to the cell that holds the formula

=Len(Dec2Bin(A1

or

=Int(1+Log(A1,2

or

=Int(Log(2*A1,2

Excel, 17 Bytes

Same as above but formatted for MS Excel

=Len(Dec2Bin(A1))

or

=Int(1+Log(A1,2))

or

=Int(Log(2*A1,2))

Taylor Scott

Posted 2016-12-27T16:05:05.810

Reputation: 6 709

8

Pyth, 3 bytes

l.B

Test suite available here.

Explanation

l.BQ    Q is implicitly appended
   Q    eval(input)
 .B     convert Q to binary string
l       len(.B(Q))

Mike Bufardeci

Posted 2016-12-27T16:05:05.810

Reputation: 1 680

Alternatively: hsl or .El, in which l computes the log base 2, and hs or .E compute ceiling. – RK. – 2018-05-14T11:29:33.627

8

Jelly, 2 bytes

BL

Converts to binary, finds length.

Rɪᴋᴇʀ

Posted 2016-12-27T16:05:05.810

Reputation: 7 410

8

C#, 63 45 31 bytes

Saved 18 bytes, thanks to Loovjo, and TuukkaX

Saved 14 bytes, thanks to Grax

 b=>1+(int)System.Math.Log(b,2);

It uses, that a decimal number n has ⌊log2(n)⌋+1 bits, which is described on this page:

Number of Bits in a Specific Decimal Integer

A positive integer n has b bits when 2^(b-1) ≤ n ≤ 2^b – 1. For example:

  • 29 has 5 bits because 16 ≤ 29 ≤ 31, or 2^4 ≤ 29 ≤ 2^5 – 1
  • 123 has 7 bits because 64 ≤ 123 ≤ 127, or 2^6 ≤ 123 ≤ 2^7 – 1
  • 967 has 10 bits because 512 ≤ 967 ≤ 1023, or 2^9 ≤ 967 ≤ 2^10 – 1

For larger numbers, you could consult a table of powers of two to find the consecutive powers that contain your number.

To see why this works, think of the binary representations of the integers 2^4 through 2^5 – 1, for example. They are 10000 through 11111, all possible 5-bit values.

Using Logarithms

The above method can be stated another way: the number of bits is the exponent of the smallest power of two greater than your number. You can state that mathematically as:

bspec = ⌊log2(n)⌋ + 1

That formula has three parts:

  • log2(n) means the logarithm in base 2 of n, which is the exponent to which 2 is raised to get n. For example, log2(123) ≈ 6.9425145. The presence of a fractional part means n is between powers of two.

  • ⌊x⌋ is the floor of x, which is the integer part of x. For example, ⌊6.9425145⌋ = 6. You can think of ⌊log2(n)⌋ as the exponent of the highest power of two in the binary representation of n.

  • +1 takes the exponent to the next higher power of two. You can think of this step as accounting for the 2^0th place of your binary number, which then gives you its total number of bits. For our example, that’s 6 + 1 = 7. You might be tempted to use the ceiling function — ⌈x⌉, which is the smallest integer greater than or equal to x — to compute the number of bits as such:

bspec = ⌈log2(n)⌉

However, this fails when n is a power of two.

Horváth Dávid

Posted 2016-12-27T16:05:05.810

Reputation: 679

You have an extra space in there ...)+ 1)... -> ...)+1.... Also, I think you can return the value directly instead of printing it. – Loovjo – 2016-12-27T21:05:32.187

You can drop it down to 31 by doing b=>1+(int)System.Math.Log(b,2); The int conversion provides the same output as Math.Floor and you don't need the using statement if you only reference System once. – Grax32 – 2016-12-28T18:35:20.593

5

C#, 32 bytes

n=>Convert.ToString(n,2).Length;

Converts the parameter to a binary string and returns the length of the string.

Yytsi

Posted 2016-12-27T16:05:05.810

Reputation: 3 582

4

Haskell, 20 bytes

succ.floor.logBase 2

Composes a function that takes logarithm base 2, floors, and adds 1.

Doorknob

Posted 2016-12-27T16:05:05.810

Reputation: 68 138

4

Befunge-93, 23 21 Bytes

&>2# /# :_1>+#<\#1_.@

Befunge is a 2D grid-based language (although I'm only using one line).

&                      take integer input
 >2# /# :_             until the top of the stack is zero, halve and duplicate it
          1>+#<\#1_    find the length of the stack
                   .@  output that length as an integer and terminate the program

Try it online!

JayDepp

Posted 2016-12-27T16:05:05.810

Reputation: 273

@JamesHolderness Thanks, I figured it could be shortened since it had so many hash/spaces, but I couldn't quite get it. – JayDepp – 2016-12-29T03:59:36.460

17 bytes – Jo King – 2018-05-16T03:41:36.013

3

Jellyfish, 4 bytes

p#bi

Try it online!

Print (p), the length (#) of the binary representation (b) of the input (i).

Martin Ender

Posted 2016-12-27T16:05:05.810

Reputation: 184 808

3

CJam, 5 bytes

ri2b,

Try it online!

Read input (r), convert to integer (i), get binary representation (2b), get length (,).

Martin Ender

Posted 2016-12-27T16:05:05.810

Reputation: 184 808

3

Octave, 19 bytes

@(x)ceil(log2(x+1))

Anonymous function that adds 1, computes binary logarithm and rounds up.

Try it online!

Luis Mendo

Posted 2016-12-27T16:05:05.810

Reputation: 87 464

1

Well, I tried ;-)

– Stewie Griffin – 2017-01-17T18:14:45.400

3

QBIC, 18 bytes

:{~2^q>a|_Xq\q=q+1

That's incredible Mike! But how does it work?

:        Read input as integer 'a'
{        Start an infinite DO-LOOP
~2^q>a   If 2 to the power of q (which is 1 by default) is greater than a
|_Xq     Then quit, printing q
\q=q+1   Else, increment q
[LOOP is closed implicitly by QBIC]

steenbergh

Posted 2016-12-27T16:05:05.810

Reputation: 7 772

3

Java 8, 34 27 bytes

For once, Java has some useful builtins! Now, we just need some shorter names...

x->x.toString(x,2).length()

Try it online!

Of course, you can do this without builtins (see Snowman's answer), but for a higher byte count.

FlipTack

Posted 2016-12-27T16:05:05.810

Reputation: 13 242

3

Octave, 19 bytes

@(x)nnz(dec2bin(x))    % or
@(x)nnz(de2bi(x)+1)    % or
@(x)nnz(de2bi(x)<2)    % or
@(x)numel(de2bi(x))    % or
@(x)rows(de2bi(x'))

Octave has two functions for converting decimal numbers to binary numbers.

dec2bin converts a number into a string of the characters 1 and 0 (ASCII-values 48 and 49). The length of the string will be equal to the necessary number of bits, unless specified otherwise. Since the characters 1 and 0 are non-zero, we can use nnz to find the number of elements like this: @(x)nnz(dec2bin(x)). This is 19 bytes, so it's tied with Luis Mendo's other Octave answer.

Can we do better using de2bi?

de2bi is a function that returns the binary numbers as a vector with the numbers 1 and 0 as integers, not characters. de2bi is obviously two bytes shorter than dec2bin, but we can no longer use nnz. We can use nnz if we either add 1 to all elements, or makes it into a logical vector with only true values. @(x)nnz(de2bi(x)+1) and @(x)nnz(de2bi(x)<2) are both 19 bytes. Using numel will also give us 19 bytes, @(x)numel(de2bi(x)).

rows is one byte shorter than numel, but de2bi returns a horizontal vector, so it must be transposed. @(x)rows(de2bi(x)') just so happens to be 19 bytes too.

Stewie Griffin

Posted 2016-12-27T16:05:05.810

Reputation: 43 471

2

Pyke, 3 bytes

b2l

Try it here!

Blue

Posted 2016-12-27T16:05:05.810

Reputation: 26 661

2

Retina,  44  23 bytes

Requires too much memory to run for large input values. Converts to unary, then repeatedly divides by 2, counting how many times until it hits zero. Byte count assumes ISO 8859-1 encoding.

.*
$*
+`^(1+)1?\1
$1_
.

Try it online

mbomb007

Posted 2016-12-27T16:05:05.810

Reputation: 21 944

1I'm not sure this is valid. This isn't a case of "it requires more memory than you'll probably have" but "it requires more memory than Retina itself can handle". In particular, the initial conversion to unary will fail for inputs of order 2^30 and above, due to limitations in Retina's implementation. – Martin Ender – 2016-12-28T09:24:07.297

If it is valid, it could be shortened a lot though: https://tio.run/nexus/retina#@6@nxaWixaWdEKdhqK1paB9jyKViGM@l9/@/saUhAA

– Martin Ender – 2016-12-28T09:28:55.207

2

Perl, 21 bytes

21 bytes, (ab)use the fact that $= must be an integer

say$==1+log(<>)/log 2

25 bytes, naïve implementation

say length sprintf"%b",<>

28 23 byte version without whitespaces

$-++while$_>>=1;say++$-

1while($i//=<>)>=1<<++$_;say


Usage

$ echo 128 | perl -E '$-++while$_>>=1;say++$-'
8
$ echo 128 | perl -E 'say length sprintf"%b",<>'
8

Zaid

Posted 2016-12-27T16:05:05.810

Reputation: 1 015

1Nice use of forcing the cast, but I think you can use 0| or $-= instead of $#_= for -1 byte! – Dom Hastings – 2016-12-28T12:58:20.280

@DomHastings yes, you're right. Thanks for the tip! – Zaid – 2016-12-28T13:03:11.410

2

JavaScript (ES6), 17 bytes

f=
a=>-~Math.log2(a)
<input type=number min=0 oninput=o.textContent=f(this.value)><div>Bits: <span id=o>

Saved 2 bytes thanks to @edc65.

Neil

Posted 2016-12-27T16:05:05.810

Reputation: 95 035

2

PHP, 21 bytes

<?=-~log($argv[1],2);
  • log(x,2) Computes log2(x)
  • ~ is the binary negation operator that also cast to int
  • - take opposite

28 bytes

<?=strlen(decbin($argv[1]));
  • decbin convert to binary
  • strlen takes length

28 bytes

<?=floor(log($argv[1],2))+1;
  • log(x,2) compute log2(x)
  • floor ... +1 takes floor plus 1

32 bytes (Thanks Titus)

for(;2**++$i<=$argv[1];);echo$i;
  • 2**$n compute 2^n ie. pow(2,n) until superior to $argv[1]

Crypto

Posted 2016-12-27T16:05:05.810

Reputation: 862

It would appear you no longer need the log(x,2) or floor ... +1 explanations – Taylor Scott – 2016-12-29T12:21:00.293

1OK, seems like a display bug (see my edit) – Crypto – 2016-12-30T06:50:34.000

1Your looping solution fails for powers of 2 (1,2,4,8 etc.); fix with <= instead of <. And for(;2**++$i<=$argv[1];);echo$i; is two bytes shorter. – Titus – 2017-02-07T19:18:33.580

2

Java 8, 43 41

v->{int b=0;for(;v>0;++b,v/=2);return b;}

Counts the bits the old fashioned way and returns the count. Lambda fits into a LongFunction<Integer>.

user18932

Posted 2016-12-27T16:05:05.810

Reputation:

I always forget that lambda syntax is so forgiving, when Java in general is more rigid. – None – 2016-12-29T19:11:54.467

I've linked your answer in mine, as I feel guilty for just cheating with builtins :) – FlipTack – 2016-12-29T19:20:36.310

1@FlipTack don't feel guilty, built-ins are not cheating (unless specified otherwise). Our answers are separate solutions so they are not duplicates either. – None – 2016-12-29T19:23:15.803

Do you not need class {void main() {}...} for Java answers? – ericw31415 – 2016-12-29T22:42:46.067

@ericw31415 unless otherwise specified, a "program or function" is allowed, and output may be to standard output or a return value. This allows non-golfing languages to be a bit more competitive because we can use functional interfaces (lambdas). – None – 2016-12-29T22:49:18.353

@Snowman Java doesn't really have functions though, right? Aren't they all methods of a class? If the class isn't defined, the method couldn't exist. – ericw31415 – 2016-12-30T00:35:37.983

@ericw31415 yes, Java has functions and yes, they must all be scoped to a class - either static, or belonging to an object with an implicit this pointer (similar to member functions in C++). Functions in the context of a lambda are a single function belonging to an implicit anonymous (compiler-generated) class that implements a functional interface. In other words, you are correct, but Java has syntactic sugar to make lambdas appear like first-class functions. – None – 2016-12-30T04:24:04.110

2@ericw31415 lambda expressions, functional literals, etc. are all allowed. only if the post specifies "full program" must you include the boilerplate (and the default is "programs or functions") – FlipTack – 2016-12-31T16:01:37.227

2Hello from the future! Increment b (or halve v) in the loop body to save 1 byte! – Jakob – 2017-08-23T01:48:03.873

2

Actually, 2 bytes

├l

Try it online!

Explanation:

├l
├   binary representation (without leading zeroes)
 l  length

Since Actually uses arbitrary-width integers, this will work for any input, so long as there is enough memory and time.

Mego

Posted 2016-12-27T16:05:05.810

Reputation: 32 998

2

Japt, 2 bytes

¢l

¢ converts the input into a base-2 string

l returns the length

Thanks ETHproductions for shaving off 3 bytes.

Oliver

Posted 2016-12-27T16:05:05.810

Reputation: 7 160

1Awesome, thanks! ¢ is a shortcut for Us2) (see the Unicode Shortcuts section of the docs), which allows you to just do ¢l for 2 bytes. (I should add an implicit U at the beginning of every program...) – ETHproductions – 2016-12-31T12:49:17.810

1

APL, 6 bytes

1+⌊2⍟⍵

Omega is the right argument, which is replaced with the number in question.

Try it online!

Jacob Utley

Posted 2016-12-27T16:05:05.810

Reputation: 121

As it is, this would require curly brackets to make it a function. However, you can make it a function train with ⌊1+2⍟⊢. (link)

– Dennis – 2016-12-27T16:41:42.193

1

Julia, 16 bytes

n->endof(bin(n))

Anonymous function.

Rɪᴋᴇʀ

Posted 2016-12-27T16:05:05.810

Reputation: 7 410

endof is shorter than length. – Dennis – 2016-12-27T16:24:06.127

1

C, 47 39 bytes

int L(uint32_t X){return X?1+L(X/2):0;}

Not using a library function. The algorithm counts the number of bits needed by shifting right (or the equivalent divide by 2) until 0.

user230118

Posted 2016-12-27T16:05:05.810

Reputation: 239

1

RProgN, 4 Bytes.

~2BL

Explained

~2BL    #
~        # Zero Space Segment, The rest of this code is interpreted as if it were a bunch of characters separated by spaces.
 2B     # Convert implicit input to Base 2
   L    # Get the length of that, and implicitly output.

Try it online!

ATaco

Posted 2016-12-27T16:05:05.810

Reputation: 7 898

"ZSS" is not an explanation of ~ to anyone who didn't already know. – WGroleau – 2016-12-28T05:32:42.460

Sorry, Added a bit of detail. – ATaco – 2016-12-28T05:36:37.303

1

Pyth - 3 bytes

Alternative 3 byte answer. Takes floor(log2(n))+1

hsl

Test Suite.

Maltysen

Posted 2016-12-27T16:05:05.810

Reputation: 25 023

1

awk, 32 bytes

Iterate 2's exponent and see when it's greater than given value. Return the value in exit:

{for(;++i<=32;)if(2^i>$0)exit i}

Run it:

$ echo 4294967295| awk '{for(;++i<=32;)if(2^i>$0)exit i}'
$ echo $?
32

James Brown

Posted 2016-12-27T16:05:05.810

Reputation: 663

1

Python 2, 28 Bytes

def f(a):print len(bin(a))-2

sonrad10

Posted 2016-12-27T16:05:05.810

Reputation: 535

2lambda a:len(bin(a))-2 – Bassdrop Cumberwubwubwub – 2016-12-28T11:03:04.617

1

C, 27 bytes

f(n){return n?1+f(n/2u):0;}

Inspired by the answer by Quentin. Uses an unsigned literal to avoid overflow when using 32-bit integers. Might be able to cut the unsigned part if int is 64-bit, but it's more interesting this way.

anatolyg

Posted 2016-12-27T16:05:05.810

Reputation: 10 719

1

Matlab, 21 Bytes

c=@(x)nnz(dec2bin(x))

Yay for anonymous functions!

Example usage:

c(6)

ans = 

     3

Owen Morgan

Posted 2016-12-27T16:05:05.810

Reputation: 221

1

Julia, 15 bytes

n->ndigits(n,2)

This is an anonymous function that wraps Julia's built-in ndigits function that counts the number of digits of the input in the given base. Here we're giving it a base of 2.

Try it online!

Alex A.

Posted 2016-12-27T16:05:05.810

Reputation: 23 761

1

J, 11 bytes

2&(1+<.@^.)

This is a monadic verb that accepts input on the right.

2&(    @^.)  NB. Base 2 logarithm of the input
     <.      NB. Floor
   1+        NB. Add 1

Could likely be improved using # (tally) and #: (binary representation) but I haven't figured that part out yet.

Try it online!

Alex A.

Posted 2016-12-27T16:05:05.810

Reputation: 23 761

1It's just #@#: – Aky – 2017-01-01T20:29:22.923

1

ForceLang, 88 bytes

Noncompeting, requires the latest interpreter release, which postdates the question. (The ln implementation used previously was too inaccurate with large values)

set i math.ln io.readnum()
set j math.ln 2
set k math.floor i.mult j.pow -1
io.write k+1

SuperJedi224

Posted 2016-12-27T16:05:05.810

Reputation: 11 342

1

Lithp, 30 bytes

 #N::((length(to-string N 2)))

Pretty simple. Convert the number to binary (to-string N 2) and return the length of the string.

Try it online!

Alternate entry (no binary builtin), 38 bytes

 #N::((if(!= 0 N)((+ 1(x(>> N 1))))0))

Try it online!

Recursively shifts right by 1 each time the function is called, until we get to 0. This is an unsigned shift, so can support the full range of 0x0 - 0xFFFFFFFF. The Lithp >> operator is equivalent to Javascript's >>> operator.

Andrakis

Posted 2016-12-27T16:05:05.810

Reputation: 361

1

Powershell, 66 48 bytes

-18 bytes thanks to @briantist

function l {[math]::floor([math]::log($args[0])/[math]::log(2))+1}

($m=[math])::floor(m::log($args[0])/m::log(2))+1

Doing anything in Powershell is complicated, but it's better than Batch! In just Batch, this challenge isn't even possible (no decimal numbers=no logarithms).

ericw31415

Posted 2016-12-27T16:05:05.810

Reputation: 2 229

Our respective PowerShell solutions use different methods, but yours can still be shortened by getting rid of function l { } because it's completely superfluous for the challenges here; $args[0] counts for args passed to the script itself. You could also do ($m=[math])::log($args[0]) and then replace the other 2 instances of [math] with $m, like $m::floor. – briantist – 2017-02-05T05:44:26.617

1

VBScript, 45 bytes

Sub l(n)
WScript.Echo Log(n)/Log(2)+1
End Sub

See result by adding l(whatever the number is) to the end of the file. Run with cscript.exe if you want the result in a command window.

ericw31415

Posted 2016-12-27T16:05:05.810

Reputation: 2 229

You may consider adding a <!-- language-all: lang-vbs --> flag to this and all of your future VBS answers, so that they may have syntax highlighting – Taylor Scott – 2017-07-22T18:00:28.747

@TaylorScott Thanks, I'll consider doing that in the future. – ericw31415 – 2017-07-23T01:01:17.513

1

Perl, 19 bytes

$_=0|1+(log)/log 2

The score includes 1 byte for the -p switch the program requires.

Try it online!

Dennis

Posted 2016-12-27T16:05:05.810

Reputation: 196 637

1Some mad golfing skills here... just when I thought there was no more room for improvement in my answer :) – Zaid – 2017-01-01T15:25:11.610

1

Javascript, 23 bytes

x=>x.toString(2).length

f=x=>x.toString(2).length
document.write(f(341)) // 9

Oliver

Posted 2016-12-27T16:05:05.810

Reputation: 7 160

1

TI-Basic, 8 bytes

1+int(logBASE(Ans,2

Timtech

Posted 2016-12-27T16:05:05.810

Reputation: 12 038

1

C, 39 36 bytes

f(n,*p){*p=0;while(n){n/=2;(*p)++;}}

Ungolfed version:

 void f(long int n, int *p)
 {
   *p=0;
    while(n!=0)
    {
      n/=2;
     (*p)++;  
    }   
  }

The main() function that accepts number from stdin, would look like this:

   int main()
   {
       int b=0
       long int num;
       scanf("%ld",&num);
       f(num,&b);
       printf("%d\n",b);
       return 0;
   }
`

Alternative:

f(long n){i=0;while(n!=0){n/=2;i++;}return i;}

Ungolfed version:

int f(int n)
{
  int i=0;

  while(n!=0)
  {
    n/=2;
    i++;

  }
   return i;
} 

Abel Tom

Posted 2016-12-27T16:05:05.810

Reputation: 1 150

You can shave off some bytes by removing "n!=0" since n evaluates as true if nonzero. – NoSeatbelts – 2017-02-22T03:22:29.953

This is also invalid, won't compile. This, however, will. p;f(n){p=0;while(n)n/=2,++p;} works with only 29 bytes. p;f(n){for(p=0;n;n/=2)++p;} works with only 27. – NoSeatbelts – 2017-02-22T03:29:33.233

1

SmileBASIC, 20 bytes

INPUT N?LEN(BIN$(N))

12Me21

Posted 2016-12-27T16:05:05.810

Reputation: 6 110

1

Ruby, 19 bytes

->i{i.to_s(2).size}

dkudriavtsev

Posted 2016-12-27T16:05:05.810

Reputation: 5 781

1

Python 2, 39 bytes

lambda x:__import__('math').frexp(x)[1]

Not even kind of the shortest, but it showcases a neat function that could be useful elsewhere!

frexp(n) represents n as n = m * 2**e with 0.5 <= abs(m) < 1 and then returns the tuple (m, e) as output. For positive integers, e is exactly the number of bits required to represent the number.

Willbeing

Posted 2016-12-27T16:05:05.810

Reputation: 457

You could save a few bytes by just using import. – Zacharý – 2017-07-19T21:58:35.480

1

Common Lisp, 39 bytes

(defun f(i)(length(format nil "~B" i)))

Try it online!

Cheldon

Posted 2016-12-27T16:05:05.810

Reputation: 91

1

Dodos, 60 bytes

	' S ' g
g
	S dab
	g S ' dab f
f
	f ' '
	S dab
'
	dip
S
	dot

Try it online!

(S computes the sum, S ' dab f divides by 2)

user202729

Posted 2016-12-27T16:05:05.810

Reputation: 14 620

0

68020 assembler, 2 4 bytes (I think)

BFFFO D0, D1
INC D1

The BFFFO instruction finds the position of the first set bit in parameter 1, and stores the result in parameter 2. I think it is a 2-byte instruction. Unfortunately, it is indexed from 0, not 1. Hence you need an INC on D1 afterwards.

CSM

Posted 2016-12-27T16:05:05.810

Reputation: 219

0

Pushy, 11 bytes

0{${h}2/;}#

Try it online!

This works by continually doing x = x // 2 until x = 0, and counting the number of divisions taken:

0            \ Push a 0 (initial counter)
 {$     ;    \ While input > 0:
   {h}       \  Increment counter
      2/     \  Floordiv input by 2
         }#  \ Output final counter

FlipTack

Posted 2016-12-27T16:05:05.810

Reputation: 13 242

0

PowerShell v3+, 37 34 bytes

param($n)(1..32|?{!($n-shr$_)})[0]

Try it online!

briantist

Posted 2016-12-27T16:05:05.810

Reputation: 3 110

1Taking input as param($n) is 3 bytes shorter -- param($n)(1..32|?{!($n-shr$_)})[0] – AdmBorkBork – 2017-01-03T17:12:42.653

@TimmyD so it is! Can't believe I missed that. – briantist – 2017-01-03T17:14:55.100

0

Groovy, 32 bytes

{Long.toBinaryString(it).size()}

This is an unnamed closure.

Try it here !

Gurupad Mamadapur

Posted 2016-12-27T16:05:05.810

Reputation: 1 791

0

J, 4 bytes

#&#:

Explanation:

#      NB. Counts length of bit list
&      NB. Connects # and #:
#:     NB. Creates list of bits

Blocks

Posted 2016-12-27T16:05:05.810

Reputation: 141

0

MATL, 2 bytes

Bn

The shortest solution in MATL seems to be just direct, by measuring the length of the binary representation (as a vector). Other options are ZlkQ, which takes the base-2 logarithm, floors it and adds 1, or YBn which converts the input to a binary string and finds the length.

B. Mehta

Posted 2016-12-27T16:05:05.810

Reputation: 763

0

K/Kona, 4 bytes

#2\:

\: gets the representation of right-hand in base left-hand - in this case, base 2 of the input. # then just counts this

k)2\:341 
1 0 1 0 1 0 1 0 1
k)#2\:341
9

Simon Major

Posted 2016-12-27T16:05:05.810

Reputation: 401

0

Python 2, 22 bytes

lambda n:len(bin(n))-2

Try it online!

Koishore Roy

Posted 2016-12-27T16:05:05.810

Reputation: 1 144

0

Befunge-98 (PyFunge), 19 16 bytes, Thanks to @JoKing

&#\<_$.@j3:/2\+1

Try it online!

19 bytes:

&0#;1+\2/:!3j@.$_\;

Try it online!

5 bytes shorter than Befunge-93 :)

IQuick 143

Posted 2016-12-27T16:05:05.810

Reputation: 1 229

0

Whitespace, 70 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][N
T   S S N
_If_0_jump_to_Label_PRINT][S S S T  S N
_Push_2][T  S T S _Integer_division][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S S _Add][S N
T   _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S T _Print_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer i = STDIN as integer
Integer r = 0
Start LOOP:
  if i is 0:
    Call function PRINT_AND_EXIT
  i = i integer-divided by 2
  r = r + 1
  Go to next iteration of LOOP

function PRINT_AND_EXIT:
  Print r as integer
  Exit with error

Example run (n=16):

Command   Explanation                 Stack       HEAP     STDIN   STDOUT  STDERR

SSSN      Push 0                      [0]
SNS       Duplicate top (0)           [0,0]
SNS       Duplicate top (0)           [0,0,0]
TNTT      Read STDIN as integer       [0,0]       {0:16}   16
TTT       Retrieve                    [0,16]      {0:16}
NSSN      Create Label_LOOP           [0,16]      {0:16}
 SNS      Duplicate top (16)          [0,16,16]   {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [0,16]      {0:16}
 SSSTSN   Push 2                      [0,16,2]    {0:16}
 TSTS     Integer-divide (16/2)       [0,8]       {0:16}
 SNT      Swap top two                [8,0]       {0:16}
 SSSTN    Push 1                      [8,0,1]     {0:16}
 TSSS     Add (0+1)                   [8,1]       {0:16}
 SNT      Swap top two                [1,8]       {0:16}
 NSNN     Jump to Label_LOOP          [1,8]       {0:16}

 SNS      Duplicate top (8)           [1,8,8]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [1,8]       {0:16}
 SSSTSN   Push 2                      [1,8,2]     {0:16}
 TSTS     Integer-divide (8/2)        [1,4]       {0:16}
 SNT      Swap top two                [4,1]       {0:16}
 SSSTN    Push 1                      [4,1,1]     {0:16}
 TSSS     Add (1+1)                   [4,2]       {0:16}
 SNT      Swap top two                [2,4]       {0:16}
 NSNN     Jump to Label_LOOP          [2,4]       {0:16}

 SNS      Duplicate top (4)           [2,4,4]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [2,4]       {0:16}
 SSSTSN   Push 2                      [2,4,2]     {0:16}
 TSTS     Integer-divide (4/2)        [2,2]       {0:16}
 SNT      Swap top two                [2,2]       {0:16}
 SSSTN    Push 1                      [2,2,1]     {0:16}
 TSSS     Add (2+1)                   [2,3]       {0:16}
 SNT      Swap top two                [3,2]       {0:16}
 NSNN     Jump to Label_LOOP          [3,2]       {0:16}

 SNS      Duplicate top (2)           [3,2,2]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [3,2]       {0:16}
 SSSTSN   Push 2                      [3,2,2]     {0:16}
 TSTS     Integer-divide (2/2)        [3,1]       {0:16}
 SNT      Swap top two                [1,3]       {0:16}
 SSSTN    Push 1                      [1,3,1]     {0:16}
 TSSS     Add (3+1)                   [1,4]       {0:16}
 SNT      Swap top two                [4,1]       {0:16}
 NSNN     Jump to Label_LOOP          [4,1]       {0:16}

 SNS      Duplicate top (1)           [4,1,1]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [4,1]       {0:16}
 SSSTSN   Push 2                      [4,1,2]     {0:16}
 TSTS     Integer-divide (1/2)        [4,0]       {0:16}
 SNT      Swap top two                [0,4]       {0:16}
 SSSTN    Push 1                      [0,4,1]     {0:16}
 TSSS     Add (4+1)                   [0,5]       {0:16}
 SNT      Swap top two                [5,0]       {0:16}
 NSNN     Jump to Label_LOOP          [5,0]       {0:16}

 SNS      Duplicate top (0)           [5,0,0]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [5,0]       {0:16}
NSSSN     Create Label_PRINT          [5,0]       {0:16}
 SNN      Discard top                 [5]         {0:16}
 TNST     Print as integer            []          {0:16}           5
                                                                            error

Program stops with an error: No exit found.

Kevin Cruijssen

Posted 2016-12-27T16:05:05.810

Reputation: 67 575

0

Brain-Flak, 48 bytes

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

Try it online!

Readable version:

({< # Start a loop

  #devide by two:
  ({<(({}[()]))>{()(<{}({}[()])>)}{}}{})

>()} # Count interations
{} # pop the zero
) # push the result

MegaTom

Posted 2016-12-27T16:05:05.810

Reputation: 3 787