Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Extracting full digits from a range

by davido (Archbishop)
on Aug 03, 2012 at 23:28 UTC ( #985366=note: print w/replies, xml ) Need Help??

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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985366]
[Discipulus]: all is well.. flying home
[Eily]: if I had a flying home I would be rather concerned I think
[jedikaiti]: If I had a flying home, I'd be pretty psyched. How cool would that be?
[jedikaiti]: The big question is, does it have autopilot?

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2018-02-21 17:33 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (285 votes). Check out past polls.