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

Pure Bash shell solution. 87 bytes.

while((n<=${#1}));do case "${1:$n:1}" in 0)printf 1;;1)printf 0;; esac;n=$((n+1));done
• Welcome to PPCG! Nice first solution! – Grant Miller Feb 24 '18 at 11:14

Perl 6, 11 bytes

{TR/10/01/}

Try it online!

Simple transliterate that turns all 1s to 0s and vice-versa.

05AB1E, 3 bytes

€_J

Explanation:

€      # Map over the digits of the (implicit) input
_     #  Negative boolean: 0 becomes 1, everything else (so the 1s) becomes 0
J    # After the map, join everything together (and output implicitly)

Whitespace, 79 bytes

[N
S S N
_Create_Label_LOOP][S S S T T   S S S T N
_Push_49][S N
S _Duplicate_49][S N
S _Duplicate_49][T  N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][T    S S T   _Subtract][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_1][S S S T  N
_Push_1][T  S S T   _Subtract][N
T   S T N
_If_0_Jump_to_Label_0][N
N
N
_Exit][N
S S T   N
_Create_Label_0][S S S T    N
_Push_1][N
S S S N
_Create_Label_1][T  N
S T _Print_integer_to_STDOUT][N
S N
N
_Jump_to_Label_LOOP]

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

Since Whitespace can only take input as integer or character, we must add a trailing character (other than 0 or 1; like a newline, space, a letter, etc.) to indicate we're done with the input-string after reading it character by character.

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

Example run: input = 100

Command       Explanation                     Stack        Heap      STDIN   STDOUT

NSSN          Create Label_LOOP               []
SSSTTSSSTN   Push 49                         
SNS          Duplicate 49                    [49,49]
SNS          Duplicate 49                    [49,49,49]
TNTS         Read STDIN as character         [49,49]      {49:49}   1
TTT          Retrieve                        [49,49]      {49:49}
TSST         Subtract (49-49)                          {49:49}
SNS          Duplicate 0                     [0,0]        {49:49}
NTSSN        If 0: Jump to Label_1                     {49:49}
NSSSN        Create Label_1                            {49:49}
TNST        Print to STDOUT as integer      []           {49:49}           0

SSSTTSSSTN   Push 49                         
SNS          Duplicate 49                    [49,49]
SNS          Duplicate 49                    [49,49,49]
TNTS         Read STDIN as character         [49,49]      {49:48}   0
TTT          Retrieve                        [49,48]      {49:48}
TSST         Subtract (49-49)                          {49:48}
SNS          Duplicate 0                     [1,1]        {49:48}
NTSSN        If 0: Jump to Label_1                     {49:48}
SSSTN        Push 1                          [1,1]        {49:48}
TSST         Subtract (1-1)                            {49:48}
NTSTN        If 0: Jump to Label_0           []           {49:48}

NSSTN        Create Label_0                  []           {49:48}
SSSTN       Push 1                                    {49:48}
NSSSN       Create Label_1                            {49:48}
TNST        Print to STDOUT as integer      []           {49:48}           1

SSSTTSSSTN   Push 49                         
SNS          Duplicate 49                    [49,49]
SNS          Duplicate 49                    [49,49,49]
TNTS         Read STDIN as character         [49,49]      {49:48}   0
TTT          Retrieve                        [49,48]      {49:48}
TSST         Subtract (49-49)                          {49:48}
SNS          Duplicate 0                     [1,1]        {49:48}
NTSSN        If 0: Jump to Label_1                     {49:48}
SSSTN        Push 1                          [1,1]        {49:48}
TSST         Subtract (1-1)                            {49:48}
NTSTN        If 0: Jump to Label_0           []           {49:48}

NSSTN        Create Label_0                  []           {49:48}
SSSTN       Push 1                                    {49:48}
NSSSN       Create Label_1                            {49:48}
TNST        Print to STDOUT as integer      []           {49:48}           1

SSSTTSSSTN   Push 49                         
SNS          Duplicate 49                    [49,49]
SNS          Duplicate 49                    [49,49,49]
TNTS         Read STDIN as character         [49,49]      {49:10}   \n
TTT          Retrieve                        [49,10]      {49:10}
TSST         Subtract (49-10)                         {49:10}
SNS          Duplicate 39                    [39,39]      {49:10}
NTSSN        If 0: Jump to Label_1                    {49:10}
SSSTN        Push 1                          [39,1]       {49:10}
TSST         Subtract (39-1)                          {49:10}
NTSTN        If 0: Jump to Label_0           []           {49:10}
NNN          Exit program                    []           {49:10}

C, 34 bytes

Fully portable (not just one or two character encodings).

f(char*s){for(;*s;)*s++^='0'^'1';}

Output is in-place modification of the string.

A less portable version would use a simple number in place of the expression '0'^'1' - e.g. 1 for ASCII or EBCDIC - saving up to 6 bytes.

Demo

#include<stdio.h>
int main(void)
{
char s[] = "10101110101010010100010001010110101001010";
f(s);
printf("%s\n", s);
}
• Did you at all read the answer? I did say that you could use 1 for ASCII or EBCDIC systems, but that's not fully portable. – Toby Speight Jan 10 at 17:04

Reticular, 15 bytes

iSBql[n1~-o]~*;

Try it online!

Explanation

i               # Read input as string.
S              # Push array of characters in the string.
B             # Push every character in the array to the stack.
q            # Reverse the stack.
l           # Push the size of the stack.
[     ]    # Push a function that does the following:
n         # Convert top of stack to int.
1~-      # Push 1, swap the top two items in the stack and subtract them.
This takes a character x in the input string to 1-x, resulting in the bit negation.
o     # Output the top item of the stack
~   # Swap the top two items in the stack.
*  # Call the above function the same number of times as length of the input string.
(That is, for each bit in the input string, negate the bit and output it.)
; # Exit

Zsh, 3230 29 bytes

Shell builtins only: specifically, the XOR operator ^.

29 bytes: <<<$[1&#1^1]${1:+$0${1:1}}     recursion, by @GammaFunction
30 bytes: for X (${(s::)1})printf$[1^X]   more efficient for, by @GammaFunction
32 bytes: for X in ${(s::)1};printf$[1^X]

Bash, 35 bytes

35 bytes: echo $[1^${1:0:1}]${1:+$0 ${1:1}} recursion, by @GammaFunction 44 bytes: for((;i<${#1};i++));{ printf $[1^${1:i:1}];}

Ruby, 37 32

$*.each_char{|x|p x==?0?1:0} • 32:$*.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.tr("01","10")

previous:

args.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

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.

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).

Would you like to answer one of these unanswered questions instead?