How do I get a checksum from unpack in hexadecimal format?
I've been trying to figure out the unpack function in Perl and can't quite figure out the whole thing.
What I have:
A string and a 16-bi开发者_Go百科t hex checksum
(e.g. "this is my string"
, "0671"
)
I need to check that "this is my string"
equals the checksum '0671'
.
So I know unpack("%16W*", $string)
will give me the 16-bit decimal value, but I need the hex representation. I know this is an easy one so please forgive my ignorance.
As you said, unpack("%16W*", $string)
gives you an integer. To convert an integer to hex, use sprintf:
my $string = "this is my string";
my $expected = '0671';
my $checksum = sprintf('%04x', unpack("%16W*", $string));
print "match\n" if $checksum eq $expected;
If you want upper-case hex digits, use %X
instead of %x
(or %04X
in this case).
Or, you could go the other way and convert your hex checksum to an integer using 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
Try unpack("b*',$string)
.
See the pack man page for syntax.
精彩评论