Replace binary form 0-> 1 and 1-> 0 value - perl

In my script, I am dealing with a binary value, and I need to replace 0-> 1 and 1-> 0 with one place.

example: input digit = 10101001 output digit = 01010110

I tried $string =~ s/1/0/; and reverse function , but I was not able to give the correct answer.

Can someone help me.

+4
source share
3 answers

Use tr :

 my $str = '10101001'; $s =~ tr/01/10/; print "$s\n"; 

Outputs:

 01010110 
+10
source

If your input line contains only two possibilities, 0 and 1 , you can use the substitution in a multi-stage approach:

 $str =~ s/1/x/g; # all 1 to x $str =~ s/0/1/g; # all 0 to 1 $str =~ s/x/0/g; # all x to 0 

This is not a bad option for languages ​​that only provide wildcards, but Perl also has an atomic translation function:

 $str =~ tr/01/10/; 

which will work just as well (better, really, since it has less code and probably less data over).

+5
source

You can also go about this and use the bitwise operator XOR ^ ...

 my $input = '10101001'; my $binval = oct( '0b'.$input ); my $result = $binval ^ 0b11111111; printf "%08b\n", $result; 

... which will also give you 01010110 .

This, of course, has a disadvantage depending on the length of the input bit string. This solution only works for 8-bit values. However, it would not be easy to generalize to any number of bits.


To add a comment to Lưu Vĩnh Phúc , you can also use the bitwise NOT ~ operator. Again, the implementation depends on the number of bits, since you need to truncate the result:

 my $input = '10101001'; my $binval = oct( '0b'.$input ); print substr( sprintf ( '%b', ~$binval ), -8 )."\n"; 
+2
source

All Articles