Jean Jean - 3 months ago 6
Perl Question

Bitwise NOT on hexadecimal numbers in Perl

I have a long string containing hexadecimal numbers. What's the best way to replace each number with its one's complement (also in hex)?

That is, if I have

$string = "d3e5d1b8 66300f40 16010f2e \ncc1e010f 00b0b802 bbd0000f e38e0098 \n"

I want to get

$string = "2b1a2e47 99bff0cf e9fef0d1 \n33e1fef0 ff4f47fd 442ffff0 1b71ff67 \n";

The solution I have right now is doing a substitution for each of the 16 hex digits

$string=~s/0/g/g; $string=~s/f/0/g; $string=~s/g/f/g;
16 times


Use tr:

$string =~ tr/0123456789abcdef/fedbca9876543210/;