Reputation: 587
In my script i am dealing with binary value and i need to replace 0->1 and 1->0 at one place.
example : input digit = 10101001 output digit = 01010110
I tried $string =~ s/1/0/;
and reverse function
but that is getting fail to give me correct out put.
can some one help me out.
Upvotes: 4
Views: 632
Reputation: 10500
You could also go mathy on this and use the bitwise XOR operator ^
...
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 the downside of being dependent on the length of the bit input string. The given solution only works for 8-bit values. It wouldn't be hard to generalize for any number of bits, though.
To incorporate Lưu Vĩnh Phúc's comment - you can also use the bitwise NOT operator ~
. Again, the implementation is dependent on the number of bits as you need to truncate the result:
my $input = '10101001';
my $binval = oct( '0b'.$input );
print substr( sprintf ( '%b', ~$binval ), -8 )."\n";
Upvotes: 2
Reputation: 881663
If your input string has only those two possibilities 0
and 1
, then you can use substitution in a multi-stage approach:
$str =~ s/1/x/g; # all 1's to x
$str =~ s/0/1/g; # all 0's to 1
$str =~ s/x/0/g; # all x's to 0
This is not a bad option for languages that only provide substitutions, but Perl also has an atomic translation feature:
$str =~ tr/01/10/;
which will work just as well (better, really, since it's less code and probably less passes over the data).
Upvotes: 5