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";
source share