0

Suppose I have a string in perl.

$a = "001010";

After manipulating a bitwise not operator, the result should be

~$a = "110101";

How can I do this in perl?

2
  • 1
    Convert the string to a number; do your bitwise manipulation; then convert it back to a string. Look at the pack()/unpack() functions (perldoc -f pack) for details on doing those conversions. Commented Apr 28, 2014 at 16:09
  • Indeed. It's pretty weird to be doing bit arithmetic on the binary representation of a number rather than on the number itself. Commented Apr 29, 2014 at 2:51

4 Answers 4

8

Or just using tr///:

$str =~ tr/01/10/;
Sign up to request clarification or add additional context in comments.

1 Comment

this is the simplest way, IMO
2

One solution is using a regex:

$a = "001010";

$a =~ s/([01])/1-$1/eg;

Comments

0

You can use oct and sprintf:

 $a = sprintf("%0".(length($a))."b", (~oct("0b".$a)) & (1 << length($a)) - 1);

2 Comments

Readability score: 0. (Not that readability counts for much in Perl :))
Also, it fails for long bit strings.
0

There Is More Than One Way To Do It:

$str = join '' => map 0+!$_, split //, $str;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.