[Question]
  [
The ancient Greeks had these things called singly and doubly even numbers. An example of a singly even number is 14. It can be divided by 2 once, and has at that point become an odd number (7), after which it is not divisible by 2 anymore. A doubly even number is 20. It can be divided by 2 twice, and then becomes 5.
Your task is to write a function or program that takes an integer as input, and outputs the number of times it is divisible by 2 as an integer, in as few bytes as possible. The input will be a nonzero integer (any positive or negative value, within the limits of your language).
Test cases:
```
14 -> 1
20 -> 2
94208 -> 12
7 -> 0
-4 -> 2
```
The answer with the least bytes wins.
**Tip:** Try converting the number to base 2. See what that tells you.
  
[Answer]
# x86\_64 machine code, 4 bytes
[The BSF (bit scan forward) instruction does exactly this](http://x86.renejeschke.de/html/file_module_x86_id_19.html)!
```
0x0f    0xbc    0xc7    0xc3
```
In gcc-style assembly, this is:
```
    .globl  f
f:
    bsfl    %edi, %eax
    ret
```
The input is given in the EDI register and returned in the EAX register as per standard 64-bit [c](/questions/tagged/c "show questions tagged 'c'") calling conventions.
Because of two's complement binary encoding, this works for -ve as well as +ve numbers.
Also, despite the documentation saying *"If the content of the source operand is 0, the content of the destination operand is undefined."*, I find on my Ubuntu VM that the output of `f(0)` is 0.
### Instructions:
* Save the above as `evenness.s` and assemble with `gcc -c evenness.s -o evenness.o`
* Save the following test driver as `evenness-main.c` and compile with `gcc -c evenness-main.c -o evenness-main.o`:
```
#include <stdio.h>
extern int f(int n);
int main (int argc, char **argv) {
    int i;
    int testcases[] = { 14, 20, 94208, 7, 0, -4 };
    for (i = 0; i < sizeof(testcases) / sizeof(testcases[0]); i++) {
        printf("%d, %d\n", testcases[i], f(testcases[i]));
    }
    return 0;
}
```
Then:
* Link: `gcc evenness-main.o evenness.o -o evenness`
* Run: `./evenness`
---
@FarazMasroor asked for more details on how this answer was derived.
I am more familiar with [c](/questions/tagged/c "show questions tagged 'c'") than the intricacies of x86 assembly, so typically I use a compiler to generate assembly code for me. I know from experience that [gcc extensions such as `__builtin_ffs()`, `__builtin_ctz()` and `__builtin_popcount()`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html) typically compile and assemble to 1 or 2 instructions on x86. So I started out with a [c](/questions/tagged/c "show questions tagged 'c'") function like:
```
int f(int n) {
    return __builtin_ctz(n);
}
```
Instead of using regular gcc compilation all the way to object code, you can use the `-S` option to compile just to assembly - `gcc -S -c evenness.c`. This gives an assembly file `evenness.s` like this:
```
    .file   "evenness.c"
    .text
    .globl  f
    .type   f, @function
f:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %eax
    rep bsfl    %eax, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   f, .-f
    .ident  "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4"
    .section    .note.GNU-stack,"",@progbits
```
A lot of this can be golfed out. In particular we know that the [c](/questions/tagged/c "show questions tagged 'c'") [calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl) for functions with `int f(int n);` signature is nice and simple - the input param is passed in the `EDI` register and the return value is returned in the `EAX` register. So we can take most of instructions out - a lot of them are concerned with saving registers and setting up a new stack frame. We don't use the stack here and only use the `EAX` register, so don't need to worry about other registers. This leaves "golfed" assembly code:
```
    .globl  f
f:
    bsfl    %edi, %eax
    ret
```
Note as @zwol points out, you can also use optimized compilation to achieve a similar result. In particular `-Os` produces exactly the above instructions (with a few additional assembler directives that don't produce any extra object code.)
This is now assembled with `gcc -c evenness.s -o evenness.o`, which can then be linked into a test driver program as described above.
There are several ways to determine the machine code corresponding to this assembly. My favourite is to use the gdb `disass` disassembly command:
```
$ gdb ./evenness
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
...
Reading symbols from ./evenness...(no debugging symbols found)...done.
(gdb) disass /r f
Dump of assembler code for function f:
   0x00000000004005ae <+0>: 0f bc c7    bsf    %edi,%eax
   0x00000000004005b1 <+3>: c3  retq   
   0x00000000004005b2 <+4>: 66 2e 0f 1f 84 00 00 00 00 00   nopw   %cs:0x0(%rax,%rax,1)
   0x00000000004005bc <+14>:    0f 1f 40 00 nopl   0x0(%rax)
End of assembler dump.
(gdb) 
```
So we can see that the machine code for the `bsf` instruction is `0f bc c7` and for `ret` is `c3`.
[Answer]
# Python, 25 bytes
```
lambda n:len(bin(n&-n))-3
```
`n & -n` zeroes anything except the least significant bit, e.g. this:
```
100010101010100000101010000
            v
000000000000000000000010000
```
We are interested in the number of trailing zeroes, so we convert it to a binary string using `bin`, which for the above number will be `"0b10000"`. Since we don't care about the `0b`, nor the `1`, we subtract 3 from that strings length.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
Æfċ2
```
In the latest version of Jelly, `ÆEḢ` (3 bytes) works.
```
Æf      Calculate the prime factorization. On negative input, -1 appended to the end.
  ċ2    Count the 2s.
```
Try it [here](http://jelly.tryitonline.net/#code=w4ZmxIsy&input=&args=MTIw).
[Answer]
# Pyth, 6 bytes
```
/P.aQ2
```
Try it [here](https://pyth.herokuapp.com/?code=%2FP.aQ2&input=120&test_suite=1&test_suite_input=3%0A14%0A20%0A120%0A92408&debug=0).
```
 P.aQ         In the prime factorization of the absolute value of the input
/    2        count the number of 2s.
```
[Answer]
# JavaScript (ES6), 18 bytes
```
n=>Math.log2(n&-n)
```
4 bytes shorter than `31-Math.clz32`. Hah.
[Answer]
# JavaScript ES6, ~~22~~ 19 bytes
```
f=x=>x%2?0:f(x/2)+1
```
Looks like recursion is the shortest route.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
ọ2
```
[Try it online!](https://tio.run/##y0rNyan8///h7l6j/4fbHzWt@f/f0ERHwchAR8HSxMjAQkfBXEdB1wQA "Jelly – Try It Online")
## How it works
```
ọ2 - Main link. Takes n on the left
ọ  - How many times is n divisible by...
 2 - ...2? 
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 5 bytes
```
Yf2=s
```
This works for all integers.
[**Try it online!**](http://matl.tryitonline.net/#code=WWYyPXM&input=LTIw)
```
Yf      % implicit input. Compute (repeated) prime factors. For negative input
        % it computes the prime factors of the absolute value, except that for
        % -1 it produces an empty array instead of a single 1
2=s     % count occurrences of "2" in the array of prime factors
```
[Answer]
## Pyth, 8 bytes
```
lec.BQ\1
```
```
     Q    autoinitialized to eval(input())
   .B     convert to binary string
  c   \1  split on "1", returning an array of runs of 0s
 e        get the last run of 0s, or empty string if number ends with 1
l         take the length
```
For example, the binary representation of `94208` is:
```
10111000000000000
```
After splitting on `1`s and taking the last element of the resulting array, this becomes:
```
000000000000
```
That's 12 zeroes, so it's "12-ly even."
This works because `x / 2` is essentially `x >> 1`—that is, a bitshift right of `1`. Therefore, a number is divisible by 2 only when the LSB is `0` (just like how a decimal number is divisible by 10 when its last digit is `0`).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 5 bytes
Now supports negative numbers. Code:
```
Äb1¡g
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4RiMcKhZw&input=LTk0MjA4)
Explanation:
```
Ä      # Abs(input)
 b     # Convert the number to binary
  1¡   # Split on 1's
    g  # Take the length of the last element
```
Uses CP-1252 encoding.
[Answer]
## Pyth, 6 bytes
```
x_.BQ1
```
Basically just
```
convert2BinString(evaluatedInput())[::-1].index("1")
```
[Answer]
## C, 36 (28) bytes
```
int f(int n){return n&1?0:f(n/2)+1;}
```
(Not testing for zero argument as a nonzero argument was specified.)
**Update (in response to comment)**: If we allow K&R style function declarations, then we can have a 28-byte version:
```
f(n){return n&1?0:f(n/2)+1;}
```
In this case, we rely on the fact that the compiler defaults both `n` and the return type of `f` to `int`. This form generates a warning with C99 though and does not compile as valid C++ code.
[Answer]
## Java 7, 39 or maybe 44 bytes
```
int s(int a){return a%2!=0?0:s(a/2)+1;}
int s(int a){return a%2!=0|a==0?0:s(a/2)+1;}
```
Yay recursion! I had to use a `!=` instead of a shorter comparison so it wouldn't overflow on negative input, but other than that it's pretty straightforward. If it's odd, send a zero. If even, add one and do it again.
There are two versions because right now output for zero is unknown. The first will recurse until the stack overflows, and output nothing, because 0 is infinitely even. The second spits out a nice, safe, but probably-not-mathematically-rigorous 0 for output.
[Answer]
# Ruby 24 bytes
My first code golf submission (yey!)
```
("%b"%$*[0])[/0*$/].size
```
**How I got here**:
First I wanted to get code that actually fulfilled the spec to get my head around the problem, so I built the method without regards to number of bytes:
```
def how_even(x, times=1)
  half = x / 2
  if half.even?
    how_even(half, times+1)
  else
    times
  end
end
```
with this knowledge I de-recursed the function into a while loop and added `$*` (ARGV) as the input and i as the count of how many times the number has been halved before it becomes odd.
```
x=$*[0];i=1;while(x=x/2)%2<1;i+=1;end;i
```
I was quite proud of this and almost submitted it before it struck me that all this dividing by two sounded a bit binary to me, being a software engineer but not so much a computer scientist this wasn't the first thing that sprung to mind.
So I gathered some results about what the input values looked like in binary:
```
input      in binary      result
---------------------------------
   14               1110   1
   20              10100   2
94208  10111000000000000  12
```
I noticed that the result was the number of positions to the left we have to traverse before the number becomes odd.
Doing some simple string manipulations I split the string on the last occurrence of 1 and counted the length of remaining 0s:
```
("%b"%$*[0])[/0*$/].size
```
using `("%b" % x)` formatting to turn a number to binary, and [String#slice](http://ruby-doc.org/core-2.2.3/String.html#method-i-slice) to slice up my string.
I have learnt a few things about ruby on this quest and look forward to more golfs soon!
[Answer]
# JavaScript (ES6), 20 bytes 19 bytes.
```
f=x=>~x%2&&1+f(x/2)
```
This is a port of the Haskell solution by @nimi to JavaScript. It uses the "short-circuit" properties of `&&` which returns its left side if it is falsey (which in this case is `-0`) or else returns its right side. To implement `odd x = 0` we therefore make the left hand side `1 - (x % 2)` which bubbles `0` through the `&&`, otherwise we recurse to `1 + f(x / 2)`.
The shaving of `1 - (x % 2)` as `(~x) % 2` is due to @Neil below, and has the strange property that causes the above function to emit `-0` for small odd numbers. This value is a peculiarity of JS's decision that integers are IEEE754 doubles; this system has a separate `+0` and `-0` which are special-cased in JavaScript to be `===` to each other. The `~` operator computes the 32-bit-signed-integer bitwise inversion for the number, which for small odd numbers will be a negative even number. (The positive number `Math.pow(2, 31) + 1` for example produces `0` rather than `-0`.) The strange restriction to the 32-bit-signed integers does not have any other effects; in particular it does not affect correctness.
[Answer]
# Perl 6, ~~23~~ 18 bytes
```
{+($_,*/2...^*%2)}
```
**usage**
```
> my &f = {+($_,*/2...^*%2)}
-> ;; $_? is raw { #`(Block|117104200) ... }
> f(14)
1
> f(20)
2
> f(94208)
12
> f(7)
0
> f(-4)
2
```
[Answer]
# J, 6 bytes
```
1&q:@|
```
Explanation:
```
     |    absolute value
1&q:      exponent of 2 in the prime factorization
```
[Answer]
# C, 37 bytes
`f(int x){return x?x&1?0:1+f(x/2):0;}`
Recursively check the last bit until it's not a 0.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes
My 100th answer.
```
⊥⍨∘~2∘⊥⍣¯1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXUsf9a541DGjzghIgHmLD603/P@obypQNk3B0sTIwIILxjOHsw6tN/kPAA "APL (Dyalog Unicode) – Try It Online")
Explanation:
```
⊥⍨∘~2∘⊥⍣¯1
    2∘⊥⍣¯1   ⍝ convert the number to binary.
   ~         ⍝ negate it
⊥⍨           ⍝ count trailing ones in the negated number,
             ⍝ effectively counting trailing zeros in the number,
             ⍝ effectively counting how many times is the number divisible by 2.
```
[Answer]
# Java, 27 bytes
```
Long::numberOfTrailingZeros
```
[Try it online!](https://tio.run/##lY49D4IwEIZ3fkVHMKFBYuIHcXDXOKiLxuFEIMXSNterCTH8dizxY@eWy733vO9dDU@I6/ujF43RSKz2M3ckJC@dykloxSdZYNxNipzlEqxlOxDqFTBfX9kSkG9PLe6s8cvwQChUdbkywMpGH3aorVbVSQG2e1MgkEZWrvtBXK2Ua24F7ssjgpDefC5Q2/5nzP4Rh9ZS0XDtiBt/hKQKSw7GyHZjh6RwOouiEXiajMKXszRZjHLMR9Hx//su6Po3)
## Explanation
The number of times a number can be divided by 2 is equal the number of 0s after the rightmost 1 in its binary representation; Java has a built-in method for finding this. Using `Long` instead of `Integer` saves 3 bytes.
See also: [`Long.numberOfTrailingZeros` documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#numberOfTrailingZeros(long))
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
2Ǒ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIyx5EiLCIiLCIyMCJd)
This one by @lyxal
```
2Ǒ # I'm running out of things to say for this comment line
 Ǒ # How many times is the input divisible by...
2  # 2
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
Eġ∆l
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJFxKHiiIZsIiwiIiwiOTQyMDgiXQ==)
Ported from the [Desmos](https://codegolf.stackexchange.com/a/247899/107299) answer.
```
Eġ∆l # 4 bytes!
E    # 2^input
 ġ   # GCD of that and the input
  ∆l # log2
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
bṘȧ1ḟ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJi4bmYyKcx4bifIiwiIiwiLTQiXQ==)
Strategy from the osabie answer. Suprised that there has been no Vyxal answer for a such a popular question. Bit twiddling also gives 5 bytes.
```
bṘȧ1ḟ # This comment line needs some love
b     # Convert to binary
 Ṙ    # Reverse
  ȧ   # Absolute value of each element in the list. This is to handle negative numbers correctly
   1ḟ # First index of 1
```
[Answer]
# [Rust](https://www.rust-lang.org), 18 bytes
```
i8::trailing_zeros
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMGGtDyF3MTMPA3N6pzUEoU026WlJWm6FptKLaysSooSM3My89Ljq1KL8oshEjeNrLnS8osUMhUy8xQMSy309GyNDBSquRSAoKAoM68kJ09RQ6m6VkknTSNTU9Oaq5arFqJzwQIIDQA)
It's a builtin :) Replace `i8` with any other integer type and it will also work.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~27~~ 15 bytes
```
$pA:2xlL,Al-L=.
```
### Explanation
```
$pA             § Unify A with the list of prime factors of the input
   :2x          § Remove all occurences of 2 in A
      lL,       § L is the length of A minus all the 2s
         Al-L=. § Unify the output with the length of A minus L
```
[Answer]
## Haskell, 28 bytes
```
f x|odd x=0|1<2=1+f(div x 2)
```
Usage example: `f 94208`-> `12`.
If the number is odd, the result is `0`, else `1` plus a recursive call with half the number.
[Answer]
# Befunge, 20
```
&:2%#|_\1+\2/#
   @.<
```
Code execution keeps moving to the right and wrapping around to the second character of the first line (thanks to the trailing `#`) until `2%` outputs `1`, which causes `_` to switch the direction to left, then `|` to up, which wraps around to the `<` on the second row, which outputs and exits. We increment the second-to-the-top element of the stack every time through the loop, then divide the top by 2.
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~29~~ 17
```
+`\b(1+)\1$
;$1
;
```
[Try it online!](http://retina.tryitonline.net/#code=K2BcYigxKylcMSQKOyQxCjs&input=LTExMTExMTExMTExMTExMTExMTEx)
2 bytes saved thanks to Martin!
Takes unary input. This repeatedly matches the largest amount of `1`s it can such that that number of `1`s matches exactly the rest of the `1`s in the number. Each time it does this it prepends a `;` to the string. At the end, we count the number of `;`s in the string.
If you want decimal input, add:
```
\d+
$0$*1
```
to the beginning of the program.
[Answer]
# Jolf, 6 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=WmxtKWoy)
```
Zlm)j2
Zl   2  count the number occurrences of 2 in
  m)j   the prime factorization of j (input)
```
Rather simple... Kudos to ETHProductions for ousting Jolf with the version that really should work!
[Answer]
## ES6, 22 bytes
```
n=>31-Math.clz32(n&-n)
```
Returns -1 if you pass 0.
[Answer]
# PARI/GP, 17 bytes
```
n->valuation(n,2)
```
[Answer]
## 6502 machine language, 7 bytes
To find the place value of the least significant 1 bit of the nonzero value in the accumulator, leaving the result in register X:
```
A2 FF E8 4A 90 FC 60
```
To run this on the [6502 simulator on e-tradition.net](http://e-tradition.net/bytes/6502/index.html), prefix it with `A9` followed by an 8-bit integer.
This disassembles to the following:
```
count_trailing_zeroes:
    ldx #$FF
loop:
    inx
    lsr a     ; set carry to 0 iff A divisible by 2, then divide by 2 rounding down
    bcc loop  ; keep looping if A was divisible by 2
    rts       ; return with result in X
```
This is equivalent to the following C, except that C requires `int` to be at least 16-bit:
```
unsigned int count_trailing_zeroes(int signed_a) {
    unsigned int carry;
    unsigned int a = signed_a;  // cast to unsigned makes shift well-defined
    unsigned int x = UINT_MAX;
    do {
        x += 1;
        carry = a & 1;
        a >>= 1;
    } while (carry == 0);
    return x;
}
```
The same works on a 65816, assuming MX = 01 (16-bit accumulator, 8-bit index), and is equivalent to the above C snippet.
]