Entry: 開発小ネタ集その2 - 任意の文字で数値を表現したりその逆だったり
開発小ネタ集その2 - 任意の文字で数値を表現したりその逆だったり
Initial post:
2009.10.10
|
Last modified:
2009.10.10
開発小ネタ集その2。任意の文字の組み合わせで数値を表現したり、数値から文字に戻したりするPerlスクリプト。暗号化ではありませんので注意。str2numはもっといい方法ないかなあ。
use strict; use warnings; ### 文字リスト our @ascii = qw( a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0 _ + - = ); my $num1 = str2num('a'); ### 1 my $num2 = str2num('='); ### 66 my $num3 = str2num('aa'); ### 67 my $num4 = str2num('aabcae'); ### 1271895443 my $str = num2str($num4); ### aabcae ### -------------- ### 文字列を数値に変換 ### -------------- sub str2num { my $hash = shift; my $num = 0; my @id_array = split(//, $hash); @id_array = reverse(@id_array); for (my $i = 0; $i < scalar @id_array; $i++) { for (my $j = 0; $j < scalar @ascii; $j++) { if ($ascii[$j] eq $id_array[$i]) { $num += (scalar @ascii ** $i) * ($j + 1); last; } if ($j == scalar @ascii - 1) { return; } } } return $num; } ### -------------- ### 数値を文字列に変換 ### -------------- sub num2str { my $idx = $_[0] - 1; my $result = ''; my $sho = int($idx / scalar @ascii); if ($sho > 0) { $result .= &num2str($sho); } return $result. $ascii[($idx % scalar @ascii)]; }
Subscribe to my RSS feed