我一直在試圖找出在Perl中的unpack函數,並不能完全弄清楚整個事情。如何從十六進制格式解壓得到校驗和?
我有什麼: 一個字符串和一個16位十六進制校驗 (例如"this is my string"
,"0671"
)
我需要檢查"this is my string"
等於校驗'0671'
。
所以我知道unpack("%16W*", $string)
會給我16位十進制值,但我需要十六進制表示。我知道這很容易,所以請原諒我的無知。
我一直在試圖找出在Perl中的unpack函數,並不能完全弄清楚整個事情。如何從十六進制格式解壓得到校驗和?
我有什麼: 一個字符串和一個16位十六進制校驗 (例如"this is my string"
,"0671"
)
我需要檢查"this is my string"
等於校驗'0671'
。
所以我知道unpack("%16W*", $string)
會給我16位十進制值,但我需要十六進制表示。我知道這很容易,所以請原諒我的無知。
正如你所說,unpack("%16W*", $string)
給你一個整數。要將整數轉換爲十六進制,使用sprintf:
my $string = "this is my string";
my $expected = '0671';
my $checksum = sprintf('%04x', unpack("%16W*", $string));
print "match\n" if $checksum eq $expected;
如果你想大寫十六進制數字,(在這種情況下或%04X
)使用%X
代替%x
。
或者,你可以使用hex走另一條路,你的十六進制校驗和轉換爲整數:
my $string = "this is my string";
my $expected = '0671';
my $checksum = unpack("%16W*", $string);
print "match\n" if $checksum == hex $expected; # now using numeric equality
的比特表示非常感謝你,你給上層溶液是正確的。這樣的生活品味,我實際上開始做我自己的我變得如此沮喪哈哈 – 2011-02-22 21:56:54