L
Looden
Hi
I'm parsing a binary string, which encodes a number.
I don't know the length of the string in advance: 1, 2, 3 or 4 bytes.
The bytes of the string are in network order.
How can I retrieve the number?
I've written this sub, there must be a better way:
sub parse_number {
my $arg = shift;
my $size = length($arg);
my $value = 0;
my $buf;
for (my $i=($size-1);$i>=0;$i--){
$buf = unpack "C", (substr $arg, $i, 1);
$value += $buf * (256**($size-$i-1));
}
return $value;
}
Note: If the length of the string was always 2 bytes, I could just do:
sub parse_n { return unpack "n", shift; }
Thanks in advance.
I'm parsing a binary string, which encodes a number.
I don't know the length of the string in advance: 1, 2, 3 or 4 bytes.
The bytes of the string are in network order.
How can I retrieve the number?
I've written this sub, there must be a better way:
sub parse_number {
my $arg = shift;
my $size = length($arg);
my $value = 0;
my $buf;
for (my $i=($size-1);$i>=0;$i--){
$buf = unpack "C", (substr $arg, $i, 1);
$value += $buf * (256**($size-$i-1));
}
return $value;
}
Note: If the length of the string was always 2 bytes, I could just do:
sub parse_n { return unpack "n", shift; }
Thanks in advance.