[英]How to generate XOR checksum for a string using perl
I am trying to generate checksum for a NEMA(GPS protocol) word using perl. 我正在尝试使用perl为NEMA(GPS协议)单词生成校验和。 A sample NEMA word is string of characters as shown below NEMA单词示例是字符串,如下所示
$GPGLL,5300.97914,N,00259.98174,E,125926,A*28
The checksum is calculated by taking XOR of all the characters between $
and *
. 校验和是通过对$
和*
之间的所有字符进行XOR计算得出的。 In this sentence the checksum is the character representation of the hexadecimal value 28. 在此句子中,校验和是十六进制值28的字符表示。
I tried the following: 我尝试了以下方法:
my $NMEA_word = 'GPGLL,5300.97914,N,00259.98174,E,125926,A';
my $uff = unpack( '%8A*', $NMEA_word );
print "Hexadecimal number: ", uc(sprintf("%x\n", $uff)), "\n";
But it doesn't seem to give a correct value. 但这似乎没有给出正确的值。 Please suggest what shall be rectified 请提出应纠正的建议
my $uff;
$uff ^= $_ for unpack 'C*', 'GPGLL,5300.97914,N,00259.98174,E,125926,A';
printf "Hexadecimal number: \U%x\n", $uff;
__END__
Hexadecimal number: 28
More functionally, 在功能上,
use List::Util 'reduce';
sub checksum {
sprintf '%02X', ord reduce { our $a ^ our $b } split //, shift;
}
print checksum('GPGLL,5300.97914,N,00259.98174,E,125926,A'), "\n";
The unpack
facility to generate a checksum adds the field values together, whereas you want then XORed. 用于生成校验和的unpack
工具将字段值加在一起,而后又需要进行异或。
This program will do what you ask. 该程序将执行您所要求的。
use strict;
use warnings;
my $NMEA_word = 'GPGLL,5300.97914,N,00259.98174,E,125926,A';
printf "Hexadecimal number: %s\n", checksum($NMEA_word);
sub checksum {
my ($string) = @_;
my $v = 0;
$v ^= $_ for unpack 'C*', $string;
sprintf '%02X', $v;
}
output 输出
Hexadecimal number: 28
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.