Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Extracting full digits from a range

by davido (Cardinal)
on Aug 03, 2012 at 23:28 UTC ( [id://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.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://985366]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-03-29 10:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found