g | x | w | all
Bytes Lang Time Link
012x8664 machine code190202T102440ZPeter Co
210Bespoke250823T063702ZJosiah W
080Tcl250529T104630Zsergiol
009Uiua240315T005756ZZylviij
nanPiet + asciipiet220718T021752ZNolan
004Thunno 2230617T091549ZThe Thon
055Desmos220718T041901ZnaffetS
026K ngn/k220720T093144Zoeuf
013Regex Perl / PCRE2 / Boost / Pythonregex220718T060543ZDeadcode
003Vyxal220718T042144ZnaffetS
006APL Dyalog Extended190917T131644ZRikedyP
011APL220718T070818ZVadim Tu
060QBasic190129T124941Zsteenber
039TSQL190129T121208Zt-clause
009Pushy190209T101350ZFlipTack
020x86 Machine Code190209T084832ZCody Gra
058C clang190129T035706Za stone
115Chip w190208T205957ZPhlarx
116Alchemist190202T043226ZJo King
609ArnoldC190202T031017ZSasha
004Jelly190128T210059ZJonathan
4139PHP190130T173617Z640KB
103JS190201T092036ZNautilus
125Alchemist190201T010550ZASCII-on
016K oK190129T185506ZGalen Iv
003Catholicon190128T222341ZOkx
091SAS190130T152456ZJosh Ell
012CJam190130T043209ZEsolangi
029C# Visual C# Interactive Compiler190129T042627ZGymhgy
025Ruby190129T235946ZReinstat
029Haskell190129T234545Zxnor
020Pure Bash190128T231510ZDigital
033JavaScript190129T152014ZMattH
013Julia 0.6190129T100136ZKirill L
00705AB1E190129T060513ZJackson
00905AB1E190129T014044ZMagic Oc
023R190129T074449ZdigEmAll
038C# Visual C# Interactive Compiler190129T061642Zdana
036APLNARS 18 chars190129T135331Zuser5898
037PowerShell190128T210211ZAdmBorkB
036Python 2190129T124254Zmdahmoun
00305AB1E190129T073159ZKevin Cr
022Perl 5190129T115135ZNahuel F
005Japt190128T221251ZShaggy
039C gcc190129T104327Znwellnho
046Java 8190129T095414ZKevin Cr
033C# Visual C# Interactive Compiler190129T095151ZKevin Cr
026Ruby190129T093641ZKirill L
012Perl 6190128T223506ZJo King
013J190129T081627ZGalen Iv
00605AB1E190129T064237ZWisław
041F# .NET Core190129T065647Zdana
005MATL190129T033706Zalephalp
031Pari/GP190129T032021Zalephalp
274Alchemist190129T014345Zბიმო
003Sledgehammer 0.2190128T232304Zlirtosia
058Wolfram Language190128T212317ZDavidC
017Wolfram Language Mathematica190128T225757Zlirtosia
035Python190128T210953ZJonathan
005MATL190128T223857ZLuis Men
006Jelly190128T203816ZMr. Xcod
040Python 2190128T204504Zovs
028JavaScript ES6190128T205942ZArnauld
012Charcoal190128T214840ZNeil
025Retina 0.8.2190128T214025ZNeil
007APL Dyalog Extended190128T210546ZAdá

x86-64 machine code, 12 bytes

This is a function you can call with the x86-64 System V calling convention, with this signature:
void binary_placevalues_withzero(uint8_t out[8] /*rdi*/, uint8_t val /*sil*/); or
void binary_placevalues_withzero(uint64_t *out /*rdi*/, uint8_t val /*sil*/); as a quick hack for making the output something you can print as one hex number for all 8 bytes.

It isolates the place values in increasing order into the output array, producing a result like 01 00 00 00 00 00 00 80 for esi = 129.

We start with mask = 1, and left-shift the mask by 1 until it overflows an 8-bit register.

nasm -l listing
    25 address   code bytes    global binary_placevalues_withzero
    26                         binary_placevalues_withzero:
    27 00000020 B101               mov  cl,1
    28                         .loop:
    29 00000022 88C8               mov  al,cl
    30 00000024 21F0               and  eax, esi     ; al,sil would cost a REX prefix 
    31 00000026 AA                 stosb             ; *rdi++ = val & mask
    32 00000027 00C9               add  cl,cl        ; left-shift the mask
    33 00000029 73F7               jnc  .loop        ; until it shifts out
    34 0000002B C3                 ret

An alternate version that only writes non-zero entries (thus producing an output array of length __builtin_popcount(val)) is also 12 bytes. This needs val zero-extended into ESI to avoid test false positives, unlike the version that doesn't skip zeros.

void binary_placevalues(uint8_t out[8] /*rdi*/, unsigned val /*esi*/);

    11                         global binary_placevalues
    12                         binary_placevalues:
    13 00000010 B001               mov  al,1
    14                         .loop:
    15 00000012 85F0               test  eax, esi    ; ESI must have its high bits clear, so high garbage in EAX doesn't matter
    16 00000014 7401               jz   .skip
    17 00000016 AA                 stosb             ; store if the mask matches
    18                         .skip:
    19 00000017 00C0               add  al,al        ; left-shift the mask
    20 00000019 73F7               jnc  .loop
    21 0000001B C3                 ret
    22                         

As usual, ISA extensions that let us save instructions cost more code bytes: a BMI1 version is 14 bytes. (https://www.felixcloutier.com/x86/BLSI.html and https://www.felixcloutier.com/x86/BLSR.html). Very efficient, though: each of these BLSI/BLSR instructions is only 1 uop.

     1                         global binary_placevalues_bmi1
     2                         binary_placevalues_bmi1:
     3                         .loop:
     4 00000000 C4E278F3DE         blsi  eax, esi    ; bit lowest-set isolate:  n &-n
     5 00000005 AA                 stosb
     6 00000006 C4E248F3CE         blsr  esi, esi    ; bit lowest-set reset: (n-1) & n, and sets ZF according to the result.
     7 0000000B 75F3               jnz .loop
     8 0000000D C3                 ret

(If there was high garbage in ESI, this would keep going, storing 0 bytes when EAX held an isolated bit outside the low 8.)

If you wanted speed, with BMI2 pdep you'd use a 64-bit mask that deposited the low 8 bits at their corresponding position within each byte. 1 uop / 3 cycle latency on Haswell/Skylake, at the cost of a 10-byte instruction to create the mask. :P But slow on Ryzen.


I'm not sure this is optimal. I don't think manually implementing n & -n and so on with xor/sub/and and so on would be a win, though.

Bespoke, 210 bytes

with a value,I extract numbers in bits
this is division/modulo with two on value
printing increased2powers,I put it out
we reduce by half,as quotient ultimately is turned to zero
printing bits of number in loop

For each bit b of the input from LSD to MSD, keeps track of 2^n and outputs 2^n * b.

Tcl, 80 bytes

proc D n {lmap c [lreverse [split [format %b $n] ""]] {expr $c*2**([incr i]-1)}}

Try it online!

Vanilla approach.

Uiua, 9 bytes

ⁿ:2▽:⇡⧻.⋯

get the bit representation as a list

⇡⧻. make a list of the same length, counting up from 1 [1, 2, ...]

▽: keep the values from the incrementing list for which there is a truthy bit in the bit representation list

ⁿ:2 2^n

Piet + ascii-piet, 88 bytes (4×22=88 codels)

My first Piet answer!

taqu ci?aqtqqiarufqqrNdsssec ?a??q??vejraimMdk??e lane???nv??rr ?Mddtqe ll esufnvsbiesue

In grid form:

taqu ci?aqtqqiarufqqrn
dsssec ?a??q??vejraimm
dk??e lane???nv??rr ?m
ddtqe ll esufnvsbiesue

As a PNG:
so small!
And with larger codels:
ah, much better!

Try Piet online!

In my best attempt at pseudocode:

n=input+1
p=256
while p>=1
  {p=p/2
  if n>p
    {n=n-p
    print p}}
  

Thunno 2, 4 bytes

LOÆ&

Attempt This Online!

Port of Jonathan Allan's Jelly answer.

Explanation

LOÆ&  # Implicit input  ->  10
L     # Lowered range   ->  [0,1,2,3,4,5,6,7,8,9]
 O    # Two power       ->  [1,2,4,8,16,32,64,128,256,512]
  Æ&  # Bitwise AND     ->  [0,2,0,8,0,0,0,0,0,0]
      # Implicit output

Desmos, 55 bytes

f(n)=2^{b[mod(floor(n/2^b),2)=1]}
b=[0...floor(log_2n)]

Port of Mr. Xcoder's Jelly answer.

Try it on Desmos!

K (ngn/k), 26 bytes

{_0.5+`exp x*`ln 2}'*|=|2\

Try it online!

My first function-less K answer. Port of Xcoder's Jelly answer.

Explanation:

{_0.5+`exp x*`ln 2}'*|=|2\      Main program.
                        2\      Convert to base 2
                       |        Reverse
                      =         Group into falsey and truthy indices
                    *|          Select the second element (i.e. truthy indices)
                   '            For each of them
{                 }             Execute a function that
      `exp x*`ln 2              Raise the argument to the power of 2
 _0.5+                          Then round it

Regex (Perl / PCRE2 / Boost / Pythonregex), 16 13 bytes

x(x((?1))\2|)

Takes its input in unary, as the length of a string of xs. Returns its result as the list of matches (each is also a string of xs whose length is the value).

Try it online! - Perl
Try it online! - Perl (test cases only)
Try it online! - PCRE2
Try it online! - Boost
Try it online! - Python import regex

This is a power of 2 regex that I came up with just for this challenge. It's possible that nobody has ever seen this before, and either way it will be useful in other challenges (so far, Number of binary partitions). It needs absolutely no context, and can capture a power of 2 anywhere within a unary string. It doesn't use any special feature other than non-atomic recursion and a standard backreference.

x            # match += 1
(            # Define subroutine (?1)
    x        # match += 1
    ((?1))   # \2 = match made by recursive call; match += \2
    \2       # match += \2
|    # or
             # Match nothing, causing a cascading pop to the top level of
             # recursion, ending the match.
)

Note that while ((?R))\1|x (10 bytes) would theoretically greedily match powers of 2 with the same end result as the 13 byte regex presented above, regex engines throw an error instead of running it because the recursive path doesn't consume any characters before calling itself. Regex is designed to be guaranteed to halt in finite time, thus is given this rule much like the one where any loop with no upper limit on its iteration count will exit after making a zero-width match. So all the methods of matching powers of 2 using recursion or nested backreferences are stuck with using \$1+2+4+...+1\$ instead of \$1\times 2\times 2\times 2\times...\$

Also note that the non-atomic recursive regex presented above is not to be confused with the PCRE1 atomic recursive regex ^(x(?1)?x|x)$ (Try it online!), which can't be adapted to match the largest power of 2 that fits in the available space, because unless it matches exactly the entire string, it ends up matching seemingly arbitrary powers of 2. And to work on any other engine besides PCRE1, it must be modified, either as ^(x(?>(?1))?x|x)$ or ^x(x(?1)?+x|x)?$ to be explicitly atomic: Try it online!

Regex (PCRE2 / Ruby), 17 14 bytes

x(x(\g<1>)\2|)

Try it online! - PCRE2
Try it online! - Ruby

This is a straight port of the 13 byte recursive regex to Ruby's subroutine call syntax.

Regex (Perl / PCRE / .NET), 16 bytes

x((?(1)\1\1|x))*

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - .NET

This power of 2 matching is based on the regex ^(\1\1|^x)*x$ (Try it online!), which uses nested backreferences. But since it must be able to start its match anywhere inside the input, it can't make use of the ^ anchor. A (?(N)set|unset) conditional is used instead, to ensure the first iteration is seeded only once.

      # tail = input number; no need to anchor, as all positive inputs match
x             # tail -= 1; head += 1
(
    (?(1)     # Only allow the second alternative to match on the first iteration,
              # when \1 is unset, and the first alternative to match on every
              # subsequent iteration.
        \1\1  # \1 *= 2; tail -= \1; head += \1
    |
        x     # \1 = 1; tail -= \1; head += \1
    )
)*            # Iterate the above as many times as possible, minimum 0
              # Return match = head

Regex (Perl / Java / PCRE / .NET), 18 bytes

x(\1\1|(?!\2)x())*

Try it online! - Perl
Try it online! - Java
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - .NET

This is a port of the Perl/PCRE/.NET version, to regex engines that lack conditionals. An empty capture \3 is used to keep track of whether the loop has finished its first iteration.

            # tail = input number; no need to anchor, as all positive inputs match
x           # tail -= 1; head += 1
(
    \1\1    # This can only match on iterations other than the first, since \1 is
            # unset on the first iteration; \1 *= 2; tail -= \1; head += \1
|
    (?!\2)  # Only allow a match on the first iteration, when \2 is unset.
    x       # \1 = 1; tail -= \1; head += \1
    ()      # \2 = 0
)*          # Iterate the above as many times as possible, minimum 0
            # Return match = head

Regex (.NET), 19 bytes

(x(x?)(?<2>\2\2)*)*

Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the list of captures on the Balancing Group \1 stack, whose lengths represent the numbers.

Try it online!

(
    x         # \1 = 1
    (x?)      # \2 = 1 or 0; \1 += \2
    (?<2>     # Alias as capture group \2
        \2\2  # \2 = \2 * 2; \1 += \2
    )*        # Iterate the above as many times as possible, minimum zero
)*            # Iterate the above as many times as possible, minimum zero, on
              # each iteration pushing the capture onto the group \1 stack.

Unlike Calculate the prime factors, in this challenge, returning the output as a list of matches golfs better than pushing it onto the Balancing Group stack, even when we take advantage of .NET's ability to alias a capture group.

Without capture group aliasing, this golfs even worse. We can't use (x((?(2)\2\2|x))*)*, because when starting a new power of 2, \2 is already set and the first iteration won't be seeded with x. And it's not just a simple matter of clearing the \2 stack with a (?<-2>)*, because that attempts to loop a zero-width match and will stop after one iteration. So, patching this either results in the monstrosity (x((?(2)\2\2(?<-2>)|x))*(?<-2>)?)* (34 bytes): Try it online!, or, slightly better, (x((?(3)\2\2|x()))*(?<-3>)?)* (29 bytes): Try it online! This is in fact comparable to not even explicitly using Balancing Groups: (x(?=(.*))((?(?=\2)x|\3\3))*)* (30 bytes): Try it online!

Regex (ECMAScript / Python or better), 27 bytes

(?=.*?(((x+)(?=\3$))*x$))\1

Try it online! - ECMAScript
Try it online! - Perl
Try it online! - Java
Try it online! - PCRE
Try it online! - Boost
Try it online! - Python
Try it online! - Ruby
Try it online! - .NET

In regex flavors that lack both nested and forward-declared backreferences, an entirely different method of matching powers of 2 must be used: ^((x+)(?=\3$))*x$ (Try it online!). This is dependent on ending exactly at the end of the string, so the capturing of the power of 2 is done inside a lookahead.

        # tail = input number; no need to anchor, as all positive inputs match
(?=
    .*?                  # Decrease tail by the minimum necessary to match:
    (                    # \1 = largest power of 2 less than or equal to tail
        (
            (x+)(?=\3$)  # Assert tail is even; tail /= 2
        )*               # Iterate the above as many times as possible, minimum 0
        x$               # Assert tail == 1
    )
)
\1                       # Return \1 as the match

Regex (Perl / PCRE / Pythonregex / Ruby / .NET), 27 bytes

x((?=(\3)?)((?(2)\2\2|x)))*

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Python import regex
Try it online! - Ruby
Try it online! - .NET

This is a port of the Perl/PCRE2/.NET version to regex engines lacking nested backreferences.

Although this version is of equal length to the ECMAScript one, it is of interest due to being much faster than it (and the recursive version) on regex engines that support it.

          # tail = input number; no need to anchor, as all positive inputs match
x                 # tail -= 1; head += 1
(
    (?=(\3)?)     # \2 = \3, or unset if \3 is unset
    (             # \3
        (?(2)     # Only allow the second alternative to match on the first
                  # iteration, when \2 is unset, and the first alternative to
                  # match on every subsequent iteration.
            \2\2  # \3 = \2 * 2; tail -= \3; head += \3
        |
            x     # \3 = 1; tail -= \3; head += \3
        )
    )
)*                # Iterate the above as many times as possible, minimum 0
                  # Return match = head

Regex (Perl / Java / PCRE / Pythonregex / Ruby / .NET), 29 bytes

x((?=(\3)?)(\2\2|(?!\4)x()))*

Try it online! - Perl
Try it online! - Java
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Python import regex
Try it online! - Ruby
Try it online! - .NET

This is a combination of the no-nested-backreferences and no-conditionals ports, and again, the proviso applies about it being faster than the ECMAScript and recursive versions.

Vyxal, 3 bytes

ʀE⋏

Try it Online!

ʀE⋏
ʀ    # Range from zero to the input number, inclusive
 E   # Calculate 2 to the power of each list item (vectorized)
  ⋏  # Bitwise AND each list element with the input number

APL (Dyalog Extended), 6 bytes

2*⍸⌽⊤⎕

2 to the * power of the indices of the true bits of the reversed binary encoding of the input

Try it online!

APL, 11 bytes

2*8-⍸⎕⊤⍨8⍴2

Explanation on example of number 86.

Input number: 86
⊤⍨8⍴2 Convert to bits: 0 1 0 1 0 1 1 0
Indexes of ones: 2 4 6 7
8- Substract from eight: 6 4 2 1
2* Powers of two: 64 16 4 2

QBasic, 62 60 bytes

INPUT n
t=2^n
WHILE n
IF t<=n THEN
?t
n=n-t
ENDIF
t=t/2
WEND

Here's a REPL, slightly expanded to not break QB.js's compiler...

How does it work?

INPUT n     gets the input
t=2^n       sets t to a power of 2, overshooting the first power of two
WHILE n     while we haven't fully deconstucted the input
IF t<=n THEN        if we found a power of two that is in this number
?t          then print it
n=n-t           and 'deconstruct' n by that amount
ENDIF
t=t/2       drop down to the next power of two and
WEND        repeat testing

Edit Saved 2 bytes, while n>0 is equivalent to while n.

TSQL, 43 39 bytes

Can't find a shorter fancy solution, so here is a standard loop. -4 bytes thanks to MickyT and KirillL

DECLARE @y int=255

,@ int=128s:PRINT @y&@ SET @/=2IF @>0GOTO s

Try it out

Pushy, 9 bytes

oBL:K2*#.

Try it online!

oB         \ Push binary digits to stack (least significant bit at the top).
  L:       \ len(stack) times do:
    K2*    \     Multiply all items by 2
       #.  \     Pop and print the top item

x86 Machine Code, 20 bytes

; ECX is the input value ('x')
; EDX is a temporary, used for manipulations of 'x'
; EAX is a counter, which will also be the return value
; EBP is a temporary holding space for the return address

           GetSumOfPowersOf2:
5D            pop    ebp              ; save return address
31 C0         xor    eax, eax         ; counter = 0

           MainLoop:
89 CA         mov    edx, ecx         ; \
F7 DA         neg    edx              ; | temp = (x & -x)
21 CA         and    edx, ecx         ; /
52            push   edx              ; push temp onto stack
40            inc    eax              ; increment counter
89 CA         mov    edx, ecx         ; \ 
4A            dec    edx              ; | x = (x & (x - 1))
21 D1         and    ecx, edx         ; /
75 F1         jne    SHORT MainLoop   ; loop while x != 0

55            push   ebp              ; restore return address
C3            ret                     ; return to return address, with result in EAX

These bytes define a function, which takes as input a single 32-bit integer argument in the ECX register (the choice of which register to pass the input in is rather arbitrary, but ECX is the one used in the __fastcall calling convention). This is the value x from the question.

x is assumed to be non-zero, since it is given that 1 <= x <= 255. This allows us to only test the loop condition at the bottom of the loop.

The bulk of the code is a big ol' loop that calculates the powers of two using binary bit-twiddling and pushes them onto the stack. On x86, the PUSH instruction pushes a register value onto the stack and requires only 1 byte to encode, so it's a natural choice. The caller of this function will then just retrieve the return values by POPing them off the stack. Although this is a non-standard convention (by convention, a function's result is either returned in a register or stored into a memory address via a pointer), it works.

Well, as long as you attend to one little detail: the fact that the CALL instruction pushes the return address onto the stack, and the fact that the RET instruction knows where to return by popping the return address pushed onto the stack by the CALL instruction. So, if we want to return values on the stack, we need to preserve the return address at the top of the function. This is done by POPing the value at the top of the stack into the EBP register for safe-keeping, PUSHing the return values onto the stack during the loop, and then PUSHing the value in EBP (the preserved return address) onto the stack at the position where the RET instruction will expect to find it.

With this arrangement, when control returns to the caller, all they'll have to do is POP off the return values. Of course, they need to know how many values to pop off the stack, so we have to maintain a counter inside of the loop. The EAX register was chosen for this counter, since in all x86 calling conventions, functions return their result in the EAX register. This function returns as its result the number of values to pop off of the stack.

The caller would do something like this to exercise the function:

    mov   ecx, 86             ; put input value ('x') into ECX for passing to function
    call  GetSumOfPowersOf2   ; call the function
    mov   ecx, eax            ; save the function's return value (number of values to pop off stack)
GetAndPrint:
    pop   eax                 ; pop value off of stack into EAX
    call  PrintValueInEAX     ; print the value stored in EAX
    dec   ecx                 ; decrement counter
    jnz   SHORT GetAndPrint   ; loop while counter != 0

C (clang), 133 110 63 58 bytes

58-byte solution thanks to @ceilingcat.

x=256;main(y){for(scanf("%d",&y);x/=2;)printf("%d ",y&x);}

Try it online!

Chip -w, 115 bytes

H!ZZ--ZZZ--ZZZ--ZZZZ-Z-ZZZ-Z-ZZt
@^))e G>)e F>)e E>).d[DC].b[Bze
a,x]dc[(' b[('ca[L'`e'*sece'A]a
 H]--b['*fa['b^-['

Try it online!

Takes a single raw byte as input, and returns some mix of 128 64 32 16 8 4 2 1 and 000 00 00 00 0 0 0 0

In the TIO, the argument -wgNN will provide this program with a byte of value 0xNN. So, -wg5c provides 0x5c. The special value -wgkk will instead generate a random byte.

Chip is a 2D language where each element can interact with its four neighbors with single bit values only. An unsmooshed version of the above would look like this:

!ZZZ--ZZZ--ZZZ--ZZZ--ZZ--ZZ--ZZ--Zt
)))---))---))---))---)---)---)---)-e
|||H  ||G  ||F  ||E  |D  |C  |B  |A
xx)]d xx]d xx]d xx]d )]d x]d x]d x]d
xxx]c ))]c xx]c x)]c x]c )]c x]c x]c
x)x]b )x]b ))]b x)]b x]b x]b )]b x]b
)xx]a xx]a )x]a )x]a x]a x]a x]a )]a

s*f

Here we can see eight blocks, one for each power of two, from left to right. Each block contains a grid specifying which bits should be turned on for each character of that power. The input bits (capital letters) are connected as switches to control whether each digit should be its actual value, or zero.

Alchemist, 116 bytes

_->In_a+c
0f+a+0d->d
0f+a+d->e
0f+g->c
0_+0f+0g+0a+0d->f
0f+0g+0a+d->Out_c+Out_" "+f
f+e->f+a
f+c->f+2g
f+0c+0e+a->a

Try it online!

Uses a different approach to the existing Alchemist answer. Instead of counting back from 128, we count upwards, which can then support any positive input.

Explanation:

_->In_a          # Get input number of a atoms
       +c        # And initialise the power of 2
0f+a+0d->d       # Divmod the input by 2
0f+a+d->e

0f+0g+0a+d->Out_c+Out_" "+f    # If there is a remainder, print the current power of 2
0_+0f+0g+0a+0d->f              # Otherwise, do nothing

f+e->f+a         # Reset the number to the division by 2
f+0c+0e+a->a     # While the number is not zero, restart the loop

f+c->f+2g        # And double the power of 2
0f+g->c

ArnoldC, 609 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE N
YOU SET US UP 0
GET YOUR ASS TO MARS N
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE I
YOU SET US UP 128
HEY CHRISTMAS TREE B
YOU SET US UP 0
STICK AROUND I
GET TO THE CHOPPER B
HERE IS MY INVITATION I
LET OFF SOME STEAM BENNET N
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE B
BULLSHIT
TALK TO THE HAND I
GET TO THE CHOPPER N
HERE IS MY INVITATION N
GET DOWN I
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER I
HERE IS MY INVITATION I
HE HAD TO SPLIT 2
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

Try it online!

I apologise.

Jelly, 4 bytes

-2 since we may output zeros in place of unused powers of 2 :)

Ḷ2*&

Try it online!

How?

Ḷ2*& - Link: integer, n         e.g. 10
Ḷ    - lowered range of n            [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
 2*  - two to the power of           [  1,  2,  4,  8, 16, 32, 64,128,256,512]
   & - bit-wise and                  [  0,  2,  0,  8,  0,  0,  0,  0,  0,  0]

PHP, 41 39 bytes

for($c=256;$c>>=1;)echo$argv[1]&$c,' ';

Try it online!

Or 38 with no fun >>= operator and PHP 5.6+:

for($x=8;$x--;)echo$argv[1]&2**$x,' ';

Or 36 with little-endian ("0 2 4 0 16 0 64 0") output:

while($x<8)echo$argv[1]&2**$x++,' ';

Really I just wanted to use the >>= operator, so I'm sticking with the 39.

Tests:

$php pow2.php 86
0 64 0 16 0 4 2 0

$php pow2.php 240
128 64 32 16 0 0 0 0

$php pow2.php 1
0 0 0 0 0 0 0 1

$php pow2.php 64
0 64 0 0 0 0 0 0

$php pow2.php 65
0 64 0 0 0 0 0 1

JS, 103 bytes

m=Math;f=a=>2**(m.floor(m.log2(a)));x=prompt()*1;y="";while(x>0&&x<256){z=f(x);y=y+" "+z;x=x-z}alert(y)

Alchemist, 125 bytes

_->In_x+128a+m
m+x+a->m+b
m+0x+a->n+a
m+0a->o+Out_b+Out_" "
n+b->n+x+c
n+0b+a->n+c
n+0a->p
o+b->o+c
o+0b->p
p+2c->p+a
p+0c->m

Try it online! or Test every input!

Explanation

_->In_x+128a+m           # Initialize universe with input, 128a (value to compare to) and m (state)
m+x+a->m+b               # If c has been halved, subtract min(a, x) from a and x and put its value into b
m+0x+a->n+a              # If x < a, continue to state n
m+0a->o+Out_b+Out_" "    # Else print and continue to state o
n+b->n+x+c               # Add min(a, x) (i.e. x) back to x, and add it to c (we're collecting a back into c)
n+0b+a->n+c              # Then, add the rest of a to c
n+0a->p                  # Then, go to state p
o+b->o+c                 # Add min(a, x) (i.e. a) to c - x _is_ greater than a and so contains it in its binary representation, so we're not adding back to x
o+0b->p                  # Then, go to state p
p+2c->p+a                # Halve c into a
p+0c->m                  # Then go to state m

K (oK), 19 16 bytes

-3 bytes thanks to ngn!

{*/x#2}'&|(8#2)\

Try it online!

oK does not have power operator, that's why I need a helper function {*/x#2} (copy 2 x times and reduce the resulting list by multiplication)

Catholicon, 3 bytes

ṫĊŻ

Try it online!

Explanation:

ṫ       Decompose         into the largest values where:
 Ċ               the input
  Ż       the bit count is truthy (equal to one)

SAS, 91 bytes

data;input n;length o $99;z=1;do while(n);if mod(n,2) then o=z||o;n=int(n/2);z+z;end;cards;

Input is entered on separate lines after the cards; statement, like so:

data;input n;length o $99;z=1;do while(n);if mod(n,2) then o=z||o;n=int(n/2);z+z;end;cards;
86
240
1
64

Outputs a dataset with a string representation of the binary values in the o variable enter image description here

Explanation:

data;
input n; /* Read a line of input */
length o $99; /* Output string (max of 99 characters) */
z=1; /* First power of 2 */
do while(n); /* While remainder is not 0 */
    if mod(n,2) then o=z||o; /* If current binary digit is 1, append power of two to start of output */
    n=int(n/2); /* Move to next binary digit */
    z+z; /* Double current power of two to get next power of two (add it to itself) */
end;
cards;
86
240
1

CJam, 12 bytes

{:T{2\#T&}%}

Try it online!

C# (Visual C# Interactive Compiler), 29 bytes

Contains 5 unprintable characters.

n=>"€@ ".Select(a=>a&n)

Explanation

//Lambda taking one parameter 'n'
n=>
//String with ASCII characters 128, 64, 32, 16, 8, 4, 2, and 1
"€@ "
//Iterate through all the chars of the above string and transform them to
.Select(a=>
//A bitwise AND operation between the integer value of the current char and the input value
a&n)

Try it online!

Ruby, 25 bytes

->n{8.times{|i|p n&2**i}}

Try it online!

Haskell, 29 bytes

(mapM(\n->[0,2^n])[7,6..0]!!)

Try it online!

Pure Bash, 20

echo $[2**{7..0}&$1]

Try it online!

Explanation

          {7..0}     # Brace expansion: 7 6 5 4 3 2 1 0
       2**{7..0}     # Brace expansion: 128 64 32 16 8 4 2 1
       2**{7..0}&$1  # Brace expansion: 128&n 64&n 32&n 16&n 8&n 4&n 2&n 1&n (Bitwise AND)
     $[2**{7..0}&$1] # Arithmetic expansion
echo $[2**{7..0}&$1] # and output

JavaScript - 33 bytes

n=>[..."01234567"].map(i=>n&2**i)

32 bytes, Oliver's suggestion

n=>[...2**29+'4'].map(x=>n&2**x)

Julia 0.6, 13 bytes

n->n&2.^(0:7)

Try it online!

05AB1E, 7 bytes

2вRƶ<oò

explanation:

2в        convert input to binary array
R         reverse array
ƶ<        multiply each item by it's index and subtract 1
oò        2^item then round down

Try it online!

05AB1E, 9 bytes

Ýoʒ›}æʒOQ

Try it online!


This is also correct for 6-bytes, but it doesn't complete in time on TIO for 86:

05AB1E, 6 bytes

ÝoæʒOQ

Try it online!

R, 27 23 bytes

bitwAnd(scan(),2^(7:0))

Try it online!

Unrolled code and explanation :

A = scan()         # get input number A from stdin
                   # e.g. A = 65

bitwAnd( A , 2^(7:0))  # bitwise AND between all powers of 2 : 2^7 ... 2^0 and A
                       # and implicitly print the result
                       # e.g. B = bitwAnd(65, c(128,64,32,16,8,4,2,1)) = c(0,64,0,0,0,0,0,1)

C# (Visual C# Interactive Compiler), 38 bytes

x=>{for(int y=8;y-->0;Print(x&1<<y));}

Try it online!

APL(NARS) 18 chars, 36 bytes

{(⍵⊤⍨8⍴2)/⌽1,2*⍳7}

test:

  f←{(⍵⊤⍨8⍴2)/⌽1,2*⍳7}
  f 86
64 16 4 2 
  f 240
128 64 32 16 
  f 1
1 
  f 64
64 
  f 3
2 1 

PowerShell, 45 37 bytes

param($a)7..0|%{1-shl$_}|?{$_-band$a}

Try it online!

Takes input $a, loops from 7 to 0, each iteration performing a bit-shift left (-shl) to formulate the powers-of-two for each exponent. We then pull out those ? (where) the number $_ shares a value -binaryand with the input number.

-8 bytes thanks to mazzy

Python 2, 36 bytes

def f(x):n=1;exec'print n&x;n*=2;'*8

Try it online!

05AB1E, 3 bytes

Ýo&

Port of @JonathanAllan's Jelly answer, so make sure to upvote him!

Contains zeros (including -loads of- trailing zeros).

Try it online or verify all test cases.

Explanation:

Ý      # Create a list in the range [0, (implicit) input]
       #  i.e. 15 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
       #  i.e. 16 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 o     # Take 2 to the power of each value
       #  → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768]
       #  → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536]
  &    # Bitwise-AND each value with the (implicit) input
       # 15 → [1,2,4,8,0,0,0,0,0,0,0,0,0,0,0,0]
       # 16 → [0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0]
       # (and output the result implicitly)

Perl 5, 22 bytes

say"@F"&2**$_ for 0..7

if newlines allowed as delimiter

22 bytes

28 bytes

Japt, 8 5 bytes

Æ&2pX

Try it

Æ&2pX     :Implicit input of integer U
Æ         :Map each X in the range [0,U)
 &        :  Bitwise AND of U with
  2pX     :  2 to the power of X

Alternative

Suggested by Oliver to avoid the 0s in the output using the -mf flag.

N&2pU

Try it

N&2pU     :Implicitly map each U in the range [0,input)
N         :The (singleton) array of inputs
 &        :Bitwise AND with
  2pX     :2 to the power of U
          :Implicitly filter and output

C (gcc), 39 bytes

f(n){for(;n;n&=n-1)printf("%d ",n&-n);}

Try it online!

Java 8, 46 bytes

n->{for(;n>0;n&=n-1)System.out.println(n&-n);}

Try it online.

Port of @Arnauld's JavaScript (ES6) answer, so make sure to upvote him!

Explanation:

n->{                     // Method with integer parameter and no return-type
  for(;n>0               //  Continue looping as long as `n` is larger than 0:
      ;                  //    After every iteration:
       n&=n-1)           //     Bitwise-AND `n` by `n-1`
    System.out.println(  //   Print with trailing newline:
      n&-n);}            //    `n` bitwise-AND `-n`

C# (Visual C# Interactive Compiler), 33 bytes

n=>{for(;n>0;n&=n-1)Print(n&-n);}

Port of @Arnauld's JavaScript (ES6) answer, so make sure to upvote him!

Try it online.

Explanation:

n=>{            // Method with integer parameter and no return-type
  for(;n>0      //  Continue looping as long as `n` is larger than 0:
      ;         //    After every iteration:
       n&=n-1)  //     Bitwise-AND `n` by `n-1`
    Print(      //   Print with trailing newline:
      n&-n);}   //    `n` bitwise-AND `-n`

Ruby, 26 bytes

->n{(0..7).map{|i|n&2**i}}

Try it online!

Same approach as Jonathan Allan's answer.

Perl 6, 16 12 bytes

-4 bytes thanks to Jonathan Allan

*+&2**all ^8

Try it online!

Returns an All Junction with 8 elements. This is a rather non-standard way of returning, but generally, Junctions can act as ordered (at least until autothreading is implemented) lists and it is possible to extract the values from one.

Explanation:

*+&              # Bitwise AND the input with
   2**           # 2 raised to the power of
      all ^8     # All of the range 0 to 7

J, 13 bytes

(2^I.)&.|.@#:

Try it online!

05AB1E, 6 bytes

bRεNo*

Try it online! or as Test Suite

Explanation

       # Implicit input n
b      # Convert to binary
 R     # Reverse
  ε    # For each digit d in the binary number
   N   # Push its index N
    o* # Compute d*2^N
       # Implicit output of list of results

F# (.NET Core), 41 bytes

fun x->Seq.map(fun y->x&&&pown 2 y)[0..7]

Try it online!

MATL, 5 bytes

BXdXB

Try it online!

Explanation

B    % Convert to binary (as a vector)
Xd   % Give a diagonal matrix with the vector on its diagonal
XB   % Convert each row of the matrix to decimal

Pari/GP, 31 bytes

n->[2^i|i<-[0..n],bittest(n,i)]

Try it online!

Alchemist, 274 bytes

_->9a+In_x+s
s+a->s+b+c
s+x->s+y+z
s+0a+0x+b->b+d+m
s+0a+0x+0b->n+e
d+m->d+2n
d+0m->e
e+n->e+m
e+0n+b->d
e+0n+0b->h
h+m->h+u+v
h+0m->t
t+y+u->t
t+0y+u->f
t+y+0u->g+p
t+0y+0u->p
g+0p+z+v->g
g+0v->f
f+c->f+a
f+z->f+x
f+u->f
f+v->f
f+y->f
f+0v+0u+0z+0c+0y+a->s
p->Out_v+Out_" "

Try it online!

Ungolfed & Serialized

The algorithm is generating the powers of two from above, subtracting them from the input, check whether it's less or equal (output & decrement value in that case) or not and repeat while having enough copies of every value, to restore stuff (reading in Alchemist is pretty much destructive).

The "states" s0X can be merged, same with nxt without changing correctness of the program by combining all the zero-rules. The order of setting up copies or cleanup doesn't matter1:

_ -> 9a + In_x + s00

# Setup copies of x and a
s00 + a -> s00 + b + c
s00 + 0a -> s01
s01 + x -> s01 + y + z
s01 + 0x + b-> b+s1 + m
s01 + 0x +0b -> n+s2

# Compute power of
s1 +  m -> s1 + 2n
s1 + 0m -> s2

s2 +  n      -> s2 + m
s2 + 0n +  b -> s1
s2 + 0n + 0b -> s3

# Duplicate the power of two
s3 + m -> s3 + u+v
s3 +0m -> tst

# Check if it's below the value
tst +  y +  u -> tst
tst + 0y +  u -> nxt0                  # if not continue
tst +  y + 0u -> go + Out_v + Out_" "  # if not equal, output & continue
tst + 0y + 0u -> Out_v + Out_" "       # if equal, output

# Decrement the current value
go + z + v -> go
go + 0v -> nxt0

# Clear & restore for "next iteration"
nxt0 + c -> nxt0 + a  # restore counter
nxt0 + 0c->nxt1
nxt1 + z -> nxt1 + x  # restore current value (possibly decremented)
nxt1 + 0z -> nxt2
nxt2 + u -> nxt2      # clean up remainder of power of two ..
nxt2 + 0u -> nxt3
nxt3 + v -> nxt3      # .. and its copy
nxt3 + 0v -> nxt4
nxt4 + y -> nxt4      # clean up the rest of comparison
nxt4 + 0y + a -> s00

Try it online!

1: The way to read it is like this: The first atom on the left-handside encodes a state (to serialize control-flow), the other atoms are counters which are replaced by the right-handside.

Sledgehammer 0.2, 3 bytes

⡔⡸⢣

Decompresses into {intLiteral[2],call[NumberExpand,2]}.

Sledgehammer is a compressor for Wolfram Language code using Braille as a code page. The actual size of the above is 2.75 bytes, but due to current rules on meta, padding to the nearest byte is counted in code size.

Wolfram Language 58 bytes

Flatten[2^#&/@(Position[Reverse@IntegerDigits[#,2],1]-1)]&

IntegerDigits[#,2] returns the binary representation of the input, #, as a list of 1's and 0's.

Reverse@ reverses that list.

(Position[...,1]-1) lists the positions of the 1's in the reversed list and decrements each position by 1.

2^#&/@ 2 is raised to the power of (position -1) for each integer in the list.

Flatten removes nested braces.

Wolfram Language (Mathematica), 17 bytes

#~NumberExpand~2&

Try it online!

Mathematica strikes again.

Python, 35 bytes

lambda n:[n&2**i for i in range(8)]

Little-endian with zeros at unused powers of 2.

Try it online!

MATL, 5 bytes

BPfqW

Try it online!

Explanation

Consider input 86 as an example.

B    % Implicit input. Convert to binary (highest to lowest digits)
     % STACK: [1 0 1 0 1 1 0]
P    % Flip
     % STACK: [0 1 1 0 1 0 1]
f    % Find: indices of nonzeros (1-based)
     % STACK: [2 3 5 7]
q    % Subtract 1, element-wise
     % STACK: [1 2 4 6]
W    % Exponential with base 2, element-wise. Implicit display
     % STACK: [2 4 16 64]

Jelly, 6 bytes

BUT’2*

Try it online!

Explanation

BUT here is an explanation (note: I had assumed that we may only output the powers of 2 themselves and nothing else):

BUT’2* – Monadic link. Takes a number N as input. Example: 86
B      – Convert N to binary.                              [1, 0, 1, 0, 1, 1, 0]
 U     – Reverse.                                          [0, 1, 1, 0, 1, 0, 1]
  T    – Truthy indices.                                   [2, 3, 5, 7]
   ’   – Decrement.                                        [1, 2, 4, 6]
    2* – Raise 2 to that power.                            [2, 4, 16, 64]

"Proof" that it works correctly. The standard representation of an integer \$ X\$ in base 2 is a list \$\{x_1, x_2, x_3,\cdots, x_n\}\$, where \$x_i\in\{0,1\},\:\forall\:\: i\in\overline{1,n}\$, such that: $$X=\sum_{i=1}^n x_i\cdot 2^{n-i}$$ The indices \$i\$ such that \$x_i=0\$ obviously have no contribution so we're only interested in finding those such that \$x_i=1\$. Since subtracting \$i\$ from \$n\$ is not convenient (the powers of two all have exponents of the form \$n-i\$, where \$i\$ is any index of a \$1\$), instead of finding the truthy indices in this list we reverse it and then find them "backwards" with UT. Now that we've found the correct indices all we have to do is raise \$2\$ to those powers.

Python 2, 43 40 bytes

f=lambda n,p=1:n/p*[1]and f(n,p*2)+[p&n]

Try it online!

JavaScript (ES6), 28 bytes

f=n=>n?[...f(n&~-n),n&-n]:[]

Try it online!

Charcoal, 12 bytes

I⮌E⮌↨N²×ιX²κ

Try it online! Link is to verbose version of code. Includes zero values (+2 bytes to remove). Explanation:

     N          Input number
    ↨           Converted to base (MSB first)
      ²         Literal 2
   ⮌            Reversed (i.e. LSB first)
  E             Map over bits
        ι       Current bit
       ×        Multiplied by
          ²     Literal 2
         X      Raised to power
           κ    Current index
 ⮌              Reversed (back to MSB first)
I               Cast to string
                Implicitly print on separate lines

Retina 0.8.2, 25 bytes

.+
$*
M!`(\G1|\1\1)*1
%`1

Try it online! Explanation:

.+
$*

Convert to unary.

M!`(\G1|\1\1)*1

Match as many powers of 2 as possible, and then an extra 1. This gives a total sum of the next power of 2. The regular expression is greedy (default), so tries to consume the largest possible power of 2 at each match. The M! then causes the matches themselves to be listed on separate lines.

%`1

Convert each line back to decimal.

APL (Dyalog Extended), 7 bytesSBCS

Anonymous tacit prefix function. Requires 0-based indexing (⎕IO←0).

2*⍸⍢⌽⍤⊤

Try it online!

2 two
* raised to the power of
 the ɩndices where true
 while
 reversed
 of
 the binary representation