http://www.perlmonks.org?node_id=985366


in reply to Extracting full digits from a range

The following code takes these steps:

  1. Unpack two four-character strings while discarding a character in the middle. These strings will represent two hex sequences.
  2. Pack the two hex strings.
  3. Unpack the packed string as two network-endian unsigned shorts.
  4. Generate a range from the low integral value to the high integral value.
  5. Pack all of the integral elements of that range.
  6. Unpack them as a series of hex strings.
  7. Print them.
my $string = "293F:2945"; my ( $low, $high ) = unpack( 'nn', pack( 'H4H4', unpack( 'A4xA4', $str +ing ) ) ); print "$_ " for unpack( '(H4)*', pack( 'n*', $low .. $high ) );

The output:

293f 2940 2941 2942 2943 2944 2945

Let's put it in a (debatably) well-named subroutine so we remember what this gem does:

sub enum_hex_range_from_string { my ( $low, $high ) = unpack( 'nn', pack( 'H4H4', unpack( 'A4xA4', $string ) ) ); return unpack( '(H4)*', pack( 'n*', $low .. $high ) ); }

Just add some camel casing randomly through the subroutine name and it would feel right at home in a PHP application.

The hardest part of coming up with something like this is keeping track of which of the many pack/unpack template tokens to use from [Hh] and [SsNnVv]. I have to admit to needing to experiment with a couple of one-liners to make sure my conversions were going the right direction.


Dave