# The shortest code to invert bit-wise a binary string

Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

10101110101010010100010001010110101001010


Write the shortest code that outputs the bit-wise inverse like so:

01010001010101101011101110101001010110101


# Jelly, 4 bytes

^1Ṿ€


Try it online!

Explanation:

First of all, if you're familiar with Jelly, you might've noticed that I'm trying to bitwise-xor with a string. That sounds all sorts of ridiculous at first, but Jelly actually supports vectorized bitwise-xor'ing with strings, where each char, if it's a digit from 1 to 9, it's treated as such, otherwise it's treated as 0. The only chars in the string will in this case be '0' and '1', being treated as themselves, as previously specified. So, bitwise-xor'ing then with 1 will return 0 ^ 1 = 1 for every '0' and 1 ^ 1 = 0 for every '1' in the string. Right now, our output is a list of 0s and 1s, so it's not yet in the correct format. We right now have to find a way to concatenate the integers into a single string, and we don't have a builtin for that. Fortunately, strings in Jelly are lists of 1-char Python strings, so we can simply take the string representation of each of the integers in the list. But wait! That builtin costs us 2 bytes, so let's see if there's a shorter builtin...and there is! Behold the uneval builtin! Unevaling an integer just takes its Jelly string representation, which, for integers, is equivalent to Python's string representation. So why not use it? That's what we'll do, to actually finish our program.

^1Ṿ€ Main link, monadic
^1   XOR each char with 1, as specified above
Ṿ€ Uneval each resulting integer


# Vim, 19 keystrokes

:s/./-&/g␤qq␁l@qq@q


␤ is Return and ␁ is CtrlA

# Explanation

:s/./-&/g␤   Negate every digit (01100 -> -0-1-1-0-0)
qq␁l@qq@q   Increment every number (-0-1-1-0-0 -> 10011)

• You could also increment every digit, 01100 ==> 12211, then swap all 2s for 0s ==> 10011. Save 1 byte doing :s/2/0/g instead of negation – roblogic Sep 8 '19 at 14:02
• @roblogic As far as i know there isn't a way to increment single digits in vim. I would have to insert separators in between each character which would waste more bytes than it saves – Herman L Sep 8 '19 at 19:41

# Japt-m, 2 bytes

^1


Try it here

# Forth (gforth), 38 36 bytes

: f 0 do dup c@ 1 xor emit 1+ loop ;


Try it online!

-2 bytes thanks to @bubbler

### Explanation

Gets the string character by character. For each character:

1. checks if it's equal to 49 and then adds -1 to the result (forth uses -1 as true).
2. Prints the space right-aligned in a space of size 1 (removes space after number that . normally outputs)

### Code Explanation

: f                \ start a new word definition
0 do             \ start counted loop from 1 to string-length
dup c@         \ duplicate the string address and get the ascii value of the char at the beginning
49 = 1+        \ check if equal to 49 and add 1 to the result (forth uses -1 as true)
1 .r           \ output right-aligned in a space of size (removes trailing space)
1+             \ increment the string address
loop             \ end the loop
;                  \ end the word definition


• Using 1 xor emit (charcode output instead of number output) gives 36 bytes. – Bubbler Oct 12 '19 at 8:31

# brainfuck, 24 bytes or 19 bytes

,[>++[->++[<]>-]>-.>>>,]


Try it online!

or

,[+[<[-->>]<--]<.,]


(this one requires an interpreter which will noop on < if the data-index is 0)

Both programs use 8-bit wrapping cells. The main part of the programs are the >++[->++[<]>-]>- and +[<[-->>]<--]< which do some rather convoluted things to flip the last bit of the number.

I'm happy I managed to beat some more 'real' languages like C and Python, not something that happens every day with bf ;)

• If you added an initial > to that first one, so it wouldn't go out of bounds, that'd be a very nice solution. One byte shorter than mine, congrats! Works with EOF->0 or EOF->no change, and doesn't assume anything about cell size, with the specified inputs. Good stuff. – Daniel Cristofani Jan 20 at 7:24
• @DanielCristofani Yeah I thought it was cool that we had two such different looking solutions of such similar size. The reason I didn't add a > at the beginning was just because I usually just use tio as my target implementation and it works there. – KSab Jan 20 at 14:40

# brainfuck, 26 bytes

,[[-[->++>]>[->>]<<<]>+.,]


This flips the last bit of each byte of input. (Assumes EOF -> 0, assumes nothing about cell size, doesn't go out of bounds to the left.)

# Cobra - 89

class P
def main
r=''
print r


string map {0 1 1 0} $s  Not quite the shortest but highly readable. # C# in LINQPad, 64 63 foreach(var c in Console.ReadLine())Console.Write((char)(c^1));  EDIT: removed one character by using XOR 1 # ECMAScript (28 bytes) for(i of prompt(r=''))r+=1-i  Just subtraction. ## Alternative 1 (28 bytes) for(i of prompt(r=''))r+=i^1  A simple bitwise not. ## Alternative 2 (29 bytes) for(i of prompt(r=''))r+=2+~i  ~'1' is -2 and ~'0' is -1, so 2+~i gives 0 for 1 and 1 for 0. ## Alternative 3 (29 bytes) for(i of prompt(r=''))r+=+!+i  The last + changes i to a number, ! converts it to a boolean (0 is false and anything else is true) and inverts it, and the first + converts it to a number (false becomes 0 and true becomes 1). Linux amd64 assembly version, 370 bytes, generates small ELF executable (392 bytes after strip --strip-all). global _start _start: mov rsi, [rsp+16] ; argv[1] xor rdx, rdx loop: mov bl, [rsi+rdx] test bl, bl jz print xor bl, 1 mov [rsi+rdx], bl inc rdx jmp loop print: mov rdi, 1 ; stdout mov rax, 1 ; write syscall mov rax, 60 ; exit xor rdi, rdi syscall  # Java - 120103 94 This is for hdante :) class I{public static void main(String[]a){for(int x:a[0].getBytes())System.out.print(49-x);}}  It takes the string as a command-line argument. • a streaming Java 8 solution (takes lines of 0 and 1): class D{public static void main(String[] b){new java.io.BufferedReader(new java.io.InputStreamReader(System.in)).lines().forEach((String i)->System.out.print(i.equals("0")?'1':'0'));}} – Janus Troelsen Jun 11 '14 at 10:45 • a solution that takes the word "random" in the question literally and makes it's own input: class C{public static void main(String[] b){new java.util.Random().ints(0,2).forEach((int i)->System.out.print(i==0?'1':'0'));}} – Janus Troelsen Jun 11 '14 at 10:46 • reads ACSII from stdin (143 bytes): class B{public static void main(String[] b)throws java.io.IOException{int c;while((c=System.in.read())!=-1)System.out.print(c=='0'?'1':'0');}} – Janus Troelsen Jun 11 '14 at 10:47 • reads everything from stdin with the Scanner trick (165 bytes): class A{public static void main(String[] b){for(char a:new java.util.Scanner(System.in).useDelimiter("\\A").next().toCharArray())System.out.print(a=='0'?'1':'0');}} – Janus Troelsen Jun 11 '14 at 10:48 • @JanusTroelsen Um, thanks, but why don't you post a separate answer? Also, your solutions are longer. – aditsu quit because SE is EVIL Jun 11 '14 at 11:08 ## ><> (6 bytes) Assuming you don't mind the code exiting with an error, the following works: {2%0=n  Example run: $ python3 fish.py binary.fish -s "100010101101111001"
011101010010000110
something smells fishy...


This errors when it runs out of values left on the stack. If it has to actually end correctly, 11 bytes works;

{2%0=nl0=?;


Example:

$python3 fish.py binary.fish -s "10111111101101001" 01000000010010110  Essentially, each piece of code is doing the same thing: { shifts the entire stack to the left, moving the first value entered in the command call to the top of the stack; 2% takes the modulus of the top value with 2 (so "1" -> 49 (ASCII code) -> 1 and "0" -> 48 -> 0); 0= pushes 0 to the stack and pops the top two values off, pushing 1 to the stack if they are equal and 0 otherwise; and n prints the numerical value of the value on top of the stack. The additional bit in the second piece just checks if there are any values left on the stack and ends if there aren't. • I don't believe this warrants an additional answer since it's so similar, but here's an alternate program to your error-less one: i:0(?;2%0=n. This one doesn't need a flag to populate the stack, so I guess it's technically 3 bytes shorter (or 2 depending on how you want to treat spaces). – cole Sep 26 '15 at 0:56 ## Python 3, 60 bytes Not the shortest solution but i wanted to see if it could be achieved without a loop. Exclusive or on a binary of ones same length as the input string (equivalent of 2**n - 1 where n is length of input). Padding with zfill was not ideal... a=input() print(bin(int(a,2)^2**len(a)-1)[2:].zfill(len(a)))  # Chicken Scheme - 85 Me thinks this problem needs more parenthesis! (display(list->string(map(lambda(s)(if(eqv? s#\0)#\1 \0))(string->list(read-line)))))  Switching display for write saves 2 more characters, at the cost of quotes around the answer. Fun fact: A little over 20% of those 85 characters above are parentheses. Achievement unlocked. # PowerShell, 33 29 Bytes $args-split0-replace1,0-join1


Similar, but distinct, from DarkAjax's answer.

Uses inline operators to split on 0's (which results in a collection of strings of 1's), replace those 1's with 0's, and then join the collection back together with 1's (i.e., replacing the 0's that were removed when we split with 1's).

# Simplex v.0.7, 3 4 bytes

Noncompeting; languages postdates question.

bTng
b    ~~ take string input
Tn  ~~ applies negation function on each character
g ~~ clear strip and output it

• @FryAmTheEggman Oh, a negation. I reade reverse as in, reverse. Editting now – Conor O'Brien Oct 27 '15 at 19:02
• Yeah a lot of people get that mixed up on this question... anyway cool lang, I hope you get an online interpreter set up soon so I can continue to feed my need to learn esolangs while also being lazy :^) – FryAmTheEggman Oct 27 '15 at 19:04
• @FryAmTheEggman XD Thanks! You bumped up the interpreter a few spaces on my priority list. (I have quite a lot going on ATM, so I'd expect the interpreter to go online sometime this weekend.) – Conor O'Brien Oct 27 '15 at 19:09

# Lua, 66 bytes

function a(b)return b:gsub("1","2"):gsub("0","1"):gsub("2","0")end


## Burlesque, 9 bytes

)-.'/'1r~


Explanation:

)-. -- decrement every character (1 -> 0, 0 -> /)
'/'1r~ -- replace / with 1


# Prolog, 73, 71, 67 bytes

q(X):-X='0',write(1);write(0).
p(X):-atom_chars(X,L),maplist(q,L).


Not an optimal language for this challenge.
Having input in string-form makes for an expensive conversion to list.
Could probably be improved on though.

Testing:
Try it out here

## ><>, 13 10 bytes

i1+:?!;2%n


Explanation:

i1+:?!;2%n

i          Input as code point
:       Duplicate the top item
?!;    Terminate if EOF
2%  Modulo the top item of the stack by two.
Because we added one earlier, this is effectively flipping the output.
n Output as integer


Try it here

• 10 bytes: i1+:?!;2%n. I don't know ><>, but is ? supposed to pop off the stack? – lirtosiast Sep 26 '15 at 5:01
• Dang. That's clever. Will do :D – clapp Sep 26 '15 at 5:03

# Java 8, 85 bytes

void i(String s) {s.chars().mapToObj(c->(char)49-(int)c).forEach(System.out::print);}

I like Java. I like streams. Gotta do both.

• Hello, and welcome to PPCG! Why is this noncompeting? – NoOneIsHere May 26 '16 at 16:27
• Want to be calm just now. – Seims May 26 '16 at 16:39
• Golfed: void j(String s){s.chars().map(c->49-c).forEach(System.out::print);} (-17) Good job otherwise. – mrco Sep 26 '16 at 13:24

# Python 2, 57535246 41 bytes

lambda s:''.join(['10'[c>'0']for c in s])


Here's another one, with a different approach:

def b(s):return''.join([str(int(not(int(c))))for c in s])


Shortened with lambda anonymity per the advice of Mego. Shortened with '10' instead of tuple of characters per advice of DLosc

(Thanks!)

• You can turn this into an unnamed lambda to make it shorter: lambda s:''.join([('1','0')[c>'0']for c in s]) – user45941 Oct 27 '15 at 20:15
• Welcome to PPCG! Here's another 5-byte savings: ('1','0') -> '10'. – DLosc Oct 27 '15 at 21:43
• Dang! I should've thought of that one! – James Murphy Oct 27 '15 at 21:47
• You can pass a generator object to ''.join, so you don't need square brackets. – FlipTack Feb 7 '17 at 19:50

## Racket 71 bytes

(λ(s)(list->string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))


Detailed version:

(define f
(λ(s)
(list->string
(map
(λ(x)
(if(eq? x #\0)
#\1
#\0))
(string->list s)))))

(f "1010111")


Output:

"0101000"


# PHP, 48 41 bytes

foreach(str_split($argv[1])as$c)echo+!$c;  Saved 7 bytes thanks to Jörg Hülsermann! Test online • wrong inversion :^( – Destructible Lemon Sep 20 '16 at 2:30 • @DestructibleWatermelon thanks, It sounded a bit obvious to me but because I didn't get the proper meaning of the question... I'm going to fix the answer. – Mario Sep 20 '16 at 6:10 • '+!$c instead of ($c>0?0:1) for the output and delete the space in the loop – Jörg Hülsermann Sep 26 '16 at 12:01 • @JörgHülsermann Great thanks! I tried to use !$cbut only 1 printed in the output, no 0, I didn't know about the + thing. Brilliant. – Mario Sep 26 '16 at 13:01

# Clora, 6 bytes (Noncompeting)

<0I?01


Explanation:

<0I Means, if 0 < I (Current input character), set flag as true

?01 If the flag is true (I is 1), output 0, else output 1

• Looks like 6 bytes to me... – DLosc Nov 11 '16 at 20:52

# SmileBASIC 3, 40 bytes

Down 10 bytes thanks to suggestions from 12Me21.

INPUT S$WHILE""<S$?!VAL(SHIFT(S$)); WEND  This doesn't print a linebreak afterwards though, so if you did this on the console you might get something like 001010101OK. Oh well, nothing about it in the question. INPUT S$             'get string
WHILE ""<S$'while input string isn't empty: ? !VAL(SHIFT(S$)); '-SHIFT a character off our string
'-find the opposite value with VAL and !
'-print that value, omitting newline
WEND                 'while end

• There's a way to do this without using VAL( – 12Me21 Feb 7 '17 at 19:50
• You could use an infinite loop and let the program end with an error: INPUT S$@L?!VAL(SHIFT(S$));:GOTO@L for 34 bytes – 12Me21 Oct 17 '17 at 19:15

# VBA, 74 44 Bytes

VBE immediate window function that takes input from cell [A1] and inverts the binary sting by replacement

?Replace(Replace(Replace([A1],1,2),0,1),2,0)


# Noether, 18 bytes

I~sL(1si/W-Pi1+~i)


Try it here!

Loops through each character in the string, inverting each character.

Explanation:

I  - Push input to stack
~s - Store the top of the stack in the variable s
L  - Pop string off the top and push its length
(  - Pop off the stack and repeat code between brackets until stack equals popped value
1  - Push the number 1
s  - Push the value of variable s
i  - Push the value of variable i (all variables are initialised to zero)
/  - Pop a string and number, n, off stack and push the character at index n
W  - Convert string to number
-  - Pop two numbers off stack and push the numbers subtracted
P  - Print top of stack
i  - Push value of variable i
1  - Push number 1
+  - Pop top two numbers and push the addition
~i - Pop top off stack and store in variable i
)  - End loop


# Cubix, 12 bytes

i?./^\'1c$@O  Try it online! cube form:  i ? . / ^ \ ' 1 c$ @ O
. . . . . . . .
. .
. .
`