Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise NOT on hexadecimal numbers in Perl

Tags:

string

regex

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 
like image 510
Jean Avatar asked Jan 20 '23 22:01

Jean


2 Answers

Use tr:

$string =~ tr/0123456789abcdef/fedbca9876543210/;
like image 117
Aoife Avatar answered Jan 29 '23 12:01

Aoife


Fixed typo: $string =~ tr/0123456789abcdef/fedcba9876543210/;

like image 35
Jakob Loose Jensen Avatar answered Jan 29 '23 12:01

Jakob Loose Jensen