# 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


## Scala, 33 bytes

print(readLine map(c=>"10"(c&1)))


# Ruby, 37 32

$*[0].each_char{|x|p x==?0?1:0}  • 32: $*[0].each_char{|x|p x==?0?1:0} – Doorknob Jun 9 '14 at 13:35

# Powershell 41

(($args-split''-ne'')|%{1-bxor$_})-join''


Explanation:

It reads the input and splits it to turn it into an array. Then it iterates through every element of the array and uses the bitwise exclusive or to turn 1 to 0 and 0 to 1, and then joins the result and prints it to console...

## Batch - 167 Bytes

@echo off&setlocal enabledelayedexpansion&set l=-1&set s=%~1&set o=%~1
:c
if defined s set/al+=1&set s=%s:~1%&goto c
for /l %%a in (%l%,-1,0)do set/p=!o:~%%a,1!<nul


Could be cut down a bit by using Powershell to get the length of the input - then again, it could be cut down a lot by using a different language.

## Python 3 - 50 bytes

r=str.replace
r(r(r(input(),'1','a'),'0','1'),'a','0')


It's not as short as some of the other ones, but it takes a different approach.

# php, 41 bytes

Where $s is the string: str_replace(array(1,0,2),array(2,1,0),$s)


This works because the str_replace() function is just a loop when given an array. This works like this:

• replace all 1 with 2
• then all 0 with 1
• then the 2 back to 0

## Groovy - 31 28 chars

edit thanks to cfrick's insightful comment:

print args[0].tr("01","10")


previous:

args[0].each{print it=="1"?0:1}

• groovy also has tr. e.g. b.tr('01','10') – cfrick Jun 10 '14 at 14:27

# JavaScript 56

a=prompt()
for(b='',r=/./g;c=r.exec(a);b+=c^1);


## Mathematica / Wolfram Language

Three solutions here, all of which assume that the argument is being passed as a string in a variable "b". If it is being passed in another format (as I think some of the other solutions here assume), shorter solutions are possible.

Method 1, using bitwise operator for 64 char

StringJoin[ToString[BitNot[#] + 2] & /@ ToExpression[Characters@b]]


Method 2 using If/Then for 45 char

StringJoin[If[# == "0", "1", "0"] & /@ Characters@b]


Method 3, operating directly on the string, for 34 char

StringReplace[b, {"0" -> "1", "1" -> "0"}]


I suspect some Mathematica wizard is going to breeze in here and do it in 15 bytes.

• @FryAmTheEggman within Mathematica, each of the -> right arrows become single →s. My character count is correct. Mathematica preps copied code for pasting by adding spaces and replacing Unicode with ASCII characters, hence the representation above. – Michael Stern Oct 27 '15 at 21:31
• We count in bytes, not characters. → is 3 bytes. – mbomb007 Sep 16 '16 at 20:07
• And, they're snippets as opposed to functions or complete programs. chat.stackexchange.com/transcript/message/32365215#32365215 – mbomb007 Sep 16 '16 at 20:35

# C, 42 bytes

main(c){for(;c=~getchar();putchar(~c^1));}


# Ruby, 48 bytes

$<.each_char{|i|print (i.ord-1).chr.gsub"/","1"}  Not the shortest, but somewhat interesting ## Java, 101 bytes class R{String r(String s){return s.replaceAll("0", "2").replaceAll("1", "0").replaceAll("2", "1");}}  Ungolfed class R{ String r(String s){ return s.replaceAll("0", "2").replaceAll("1", "0").replaceAll("2", "1"); } }  • I think you misunderstood the task ... it was not to reverse the order, but to swap 1 and 0. – Paŭlo Ebermann Nov 1 '15 at 2:51 • @PaŭloEbermann, corrected it.. Thanks – The Coder Nov 2 '15 at 4:50 # Vitsy, 13 12 Bytes Byte size reduced by newest version ending execution on end of file*. I\[i1+2M]l\N I\ Repeat everything in the [] for input stack's length. [i1+2M] Grab an item from the input, add 1 and modulo 2 (to invert the number). l\ Repeat the next character for the currently active program stack's length. N Output the top item of the stack as a number.  *In situations that don't involve special cases. ## Pyth, 8 bytes VwpCxCN1 Vw for every char in input CN compute char code of char x 1 xor with 1 C convert from int to char p print  # pb, 46 bytes (non-competing) ^w[B!0]{w[B=48]{vb[1]^b[0]}>}vw[X!0]{<b[48+B]}  pb is newer than this challenge is, so it can't compete. Oh well. In pb, the input lives at Y=-1. This program loops over the whole input, putting a 1 below any bytes in the input with a value of 48, or '0'. At the end of the input, it goes back to Y=0 and heads right, adding 48 to everything. Spaces that were left alone become 48=='0', spaces with a 1 value become 49=='1'. Explained: ^w[B!0]{ # For each byte of input: w[B=48]{ # While byte == '0': vb[1]^ # Place a 1 on the canvas below it b[0] # Clear input char (just to break loop) } >} vw[X!0]{< # For each point on the canvas below the input: b[48+B] # Add 48 to the existing value (convert digit to ASCII) }  # Beam, 54 bytes While I having some fun playing with beam, hears the shortest I've managed to do for this one so far. All the unused spaces are a wee bit annoying, but I might be able to compress this a wee bit more. '''''''>+++++\ v+<--n<rSP(++ / Hu(< (@ r^ >@pS r^  Boiled down it compares the the ascii value of STDIN to the ascii value of 1 and decrements if 1 or increments otherwise. It doesn't throw errors or anything if non zeros or ones are encountered. Try it in the snippet var ITERS_PER_SEC = 100000; var TIMEOUT_SECS = 50; var ERROR_INTERRUPT = "Interrupted by user"; var ERROR_TIMEOUT = "Maximum iterations exceeded"; var ERROR_LOSTINSPACE = "Beam is lost in space"; var code, store, beam, ip_x, ip_y, dir, input_ptr, mem; var input, timeout, width, iterations, running; function clear_output() { document.getElementById("output").value = ""; document.getElementById("stderr").innerHTML = ""; } function stop() { running = false; document.getElementById("run").disabled = false; document.getElementById("stop").disabled = true; document.getElementById("clear").disabled = false; document.getElementById("timeout").disabled = false; } function interrupt() { error(ERROR_INTERRUPT); } function error(msg) { document.getElementById("stderr").innerHTML = msg; stop(); } function run() { clear_output(); document.getElementById("run").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("clear").disabled = true; document.getElementById("input").disabled = false; document.getElementById("timeout").disabled = false; code = document.getElementById("code").value; input = document.getElementById("input").value; timeout = document.getElementById("timeout").checked; code = code.split("\n"); width = 0; for (var i = 0; i < code.length; ++i){ if (code[i].length > width){ width = code[i].length; } } console.log(code); console.log(width); running = true; dir = 0; ip_x = 0; ip_y = 0; input_ptr = 0; beam = 0; store = 0; mem = []; input = input.split("").map(function (s) { return s.charCodeAt(0); }); iterations = 0; beam_iter(); } function beam_iter() { while (running) { var inst; try { inst = code[ip_y][ip_x]; } catch(err) { inst = ""; } switch (inst) { case ">": dir = 0; break; case "<": dir = 1; break; case "^": dir = 2; break; case "v": dir = 3; break; case "+": if(++beam > 255) beam = 0; break; case "-": if(--beam < 0) beam = 255; break; case "@": document.getElementById("output").value += String.fromCharCode(beam); break; case ":": document.getElementById("output").value += beam; break; case "/": dir ^= 2; break; case "\\": dir ^= 3; break; case "!": if (beam != 0) { dir ^= 1; } break; case "?": if (beam == 0) { dir ^= 1; } break; case "_": switch (dir) { case 2: dir = 3; break; case 3: dir = 2; break; } break; case "|": switch (dir) { case 0: dir = 1; break; case 1: dir = 0; break; } break; case "H": stop(); break; case "S": store = beam; break; case "L": beam = store; break; case "s": mem[beam] = store; break; case "g": store = mem[beam]; break; case "P": mem[store] = beam; break; case "p": beam = mem[store]; break; case "u": if (beam != store) { dir = 2; } break; case "n": if (beam != store) { dir = 3; } break; case "": --store; break; case "'": ++store; break; case ")": if (store != 0) { dir = 1; } break; case "(": if (store != 0) { dir = 0; } break; case "r": if (input_ptr >= input.length) { beam = 0; } else { beam = input[input_ptr]; ++input_ptr; } break; } // Move instruction pointer switch (dir) { case 0: ip_x++; break; case 1: ip_x--; break; case 2: ip_y--; break; case 3: ip_y++; break; } if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) { error(ERROR_LOSTINSPACE); } ++iterations; if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) { error(ERROR_TIMEOUT); } } } <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code: <br> <textarea id="code" rows="8" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''''>+++++\ v+<--n<rSP(++ / Hu(< (@ r^ >@pS r^</textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">10101110101010010100010001010110101001010</textarea> <p>Timeout: <input id="timeout" type="checkbox" checked="checked">&nbsp; <br> <br> <input id="run" type="button" value="Run" onclick="run()"> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled"> <input id="clear" type="button" value="Clear" onclick="clear_output()">&nbsp; <span id="stderr" style="color:red"></span> </p>Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> </div> # Javascript, 81 Bytes: function(s){return s.replace(/1/g,'a').replace(/0/g,'b').replace(/a/g,0).replace(/b/g,1)}  ## Test =>"1001101" <="0110010" • function(s){return s.replace(/1/g,'a').replace(/0/g,'1').replace(/a/g,'0')} is shorter. – mbomb007 Sep 16 '16 at 20:00 • @mbomb007 Oh thanks! I didn't notice that redundancy in mine. Mind if I add that to my original post? – Fuzzyzilla Sep 17 '16 at 21:34 # TeaScript, 8 bytes xl(#l^1) x //input l(# //loops through every character of the input l^1 //find the inverse of each character )  Try it online at its online interpreter (DOES NOT WORK IN CHROME). • With TeaScript 3 this can be xl#l^1 – Downgoat Feb 5 '16 at 5:34 ## Clojure, 41 bytes (fn[b](apply str(map #(if(= %\1)\0\1)b)))  ## Hoon, 34 bytes |*(* tape(turn +< (cury mix 1)))  Stole Dennis' method for using char xor 1 to switch between '0' and '1'. Return a gate that maps over the tape given, and calls (mix n 1) (binary xor) for each element, then cast the resulting list back to a tape. In Hoon, the entire memory model is a binary tree of bignums. All code is evaluated on this tree, called the 'subject'. +< is "tree navigation syntax"; instead of specifying a name for the compiler to resolve into an axis of the subject, you can provide the axis yourself with alternating characters of +/- and </> to walk the tree. Code within a gate is evaluated on a subject that has the arguments it was called with placed at +<, so we can reference the arguments directly without having to assign a name to them. |* creates a wet gate, essentially a generic function, that is typechecked at the callsite with a monomorphized version of the gate. This lets us use * as the sample for the gate instead of having to use |=(tape code) - as long as the type of the arguments at the callee are a valid list, so that ++turn typechecks. > %. "10101110101010010100010001010110101001010" |*(* tape(turn +< (cury mix 1))) "01010001010101101011101110101001010110101"  • Answers using languages and language features that are newer than the challenge are not allowed and must be marked "non-competing". Is anything you're using from newer than Jun 7 '14 at 20:20? github.com/urbit/urbit/commits/master?page=48 – mbomb007 Sep 16 '16 at 19:56 • @mbomb007 I first started using Urbit on 9/28/14, and the only major Hoon update was recently (164k to 151k), which doesn't affect that snippet. I'll have to check, but I'm quite sure that this is valid. – RenderSettings Sep 19 '16 at 18:00 # 𝔼𝕊𝕄𝕚𝕟, 13 chars / 23 bytes (non-competing) ô⟦ï]ć⇝a^1)ø⬯)  Try it here (Firefox only). • I think this is technically invalid, because the language was invented after the challenge. – lirtosiast Oct 28 '15 at 5:27 • But it doesn't have any advantage specific to the challenge... – Mama Fun Roll Oct 28 '15 at 13:37 # Swift 3 (40 bytes) As a closure expression that takes x as input and returns a String: {x in String(cString:x.utf8.map{$0^1})}


## Explanation

// make a function…
let invert = { (x: String) in

// …that will xor each UInt8 character in the input string
let y = x.utf8.map { \$0 ^ 1 }

// …and create String from the resultant [UInt8]
String(cString: y)
}


# Gogh, 5 bytes

{n!}m


This takes the logical not of the integer value of each character in the string.

# Java, 55 bytes

a->a.replace('0','2').replace('1','0').replace('2','1')


This is a java.util.function.UnaryFunction<String>.

# Turtlèd, 24 bytes (non-competing)

' !-[*+.(1'0r)(0'1r)_]'


[note trailing space]

beating the non golf langs, in a task this language is not really designed for :)

## Explanation

'[space]                      write space over initial square
!                           take input into string variable
-                          decrement the string pointer (used when writing char from string)
[*               ]        while current cell is not *
+.                      increment string pointer, write pointed char from string
(1'0r)                if cell is 1, write 0, move right
(0'1r)          if cell is 0, write 1, move right
_         EOF checker: if end of string var, write *, else [space]
'[space]write space on cell (asterisk must be here)
[implicit]     remove trailing and leading spaces and newlines, print grid.


## Python 3 - 59 41 bytes

( -18 bytes thanks to @Mego)

lambda s:''.join(str(1-int(c))for c in s)

• Welcome to PPCG! This solution is valid in both Python 2 and Python 3. There's quite a few improvements you can make, though. 1) By using a lambda function instead of a named function, you can omit the return statement: lambda s:''.join('1'if c=='0'else'0'for c in list(s)). 2) Strings are iterable, so you can replace list(s) with simply s). 3) Using boolean arithmetic on integer values is shorter: str(1-int(c)) instead of '1'if c=='0'else'0'. If you're willing to restrict your answer to Python 2 only, 1-int(c) is even shorter. – Mego Sep 20 '16 at 4:43
• How'd you know I'm new here! Thanks for your suggestions, editing my answer now! I'd rather keep it compatible to both py3 and py2 though. – Biarity Sep 20 '16 at 11:10
• I know you're new here because I found your answer in the review queue for answers posted by new users. – Mego Sep 20 '16 at 11:11

# Reticular, 13 bytes

iSBl[:0Eo]~*;


Try it online! Obviously non-competing, as language postdates question.

### Explanation

iSBl[:0Eo]~*;
i              take one line of input
S             convert string to array of chars
B            merge array with stack
l           push the length
[    ]~*   active the inside (length) times
:0        push the string "0"
E       check for equality
o      output
;  terminate program


# Python 3, 57 bytes

print(''.join(['0' if i=='1' else '1' for i in input()]))


# Java, 97 bytes

Inspired by a comment from 2 years ago @hdante ...

Golfed version:

String d(String s){String r="";for(int i=0;i<s.length();)r(s.charAt(i++)=='0')?"1":"0";return r;}


Ungolfed version:

String d(String s)
{
String r = "";
for (int i = 0; i < s.length();)
r += (s.charAt(i++) == '0') ? "1" : "0";
return r;
}


Nothing too fancy ...

# C#, 47 44 bytes

as an anonymous function takes a string and returns a string

s=>s.Aggregate("",(a,b)=>a+(b>'0'?'0':'1'));


or as an anonymous function takes a string and prints the inverted, also in 47 bytes

s=>{foreach(var c in s)Write(c=='0'?'1':'0');};
`

## protected by Community♦Jan 11 at 5:12

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).