A primitive hex version of the seq gnu utility, written in perl

From Svendsen Tech PowerShell Wiki
Jump to: navigation, search



Primitive Hex Version of seq

NB! This version is deprecated in favour of the one I describe in this article.

Once I was asked for a "hex version of seq", as the GNU utility seq apparently doesn't support hexadecimal values. So I spent 5 minutes writing a simple Perl version. This simple utility/script will enumerate hexadecimal values between a specified range. You supply a start hex and an end hex, and get everything in between (including the start and end hexes you specify).

The Help Text

Very extensive:

$ perl seqhex.pl
Usage: seqhex.pl <start_hex> <end_hex>

Example Use

A couple of quick examples. I assume I don't need to document this too extensively...

At a Linux Bash Prompt

$ perl seqhex.pl 01 20
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
10
11
12
13
14
15
16
17
18
19
1a
1b
1c
1d
1e
1f
20

From PowerShell on Windows

# The start hex needs to be smaller than the end hex (or equal, which isn't very useful)
PS E:\temp> perl .\seqhex.pl bb aa
Error: Start hex (bb) larger than end hex (aa)
Start decimal: 187 -- end decimal: 170

PS E:\temp> perl .\seqhex.pl aa bb
aa
ab
ac
ad
ae
af
b0
b1
b2
b3
b4
b5
b6
b7
b8
b9
ba
bb
PS E:\temp>

Source Code

#!/usr/bin/perl

# Author: Joakim Svendsen, Svendsen Tech
# A primitive hex version of the 'seq' GNU utility, written in Perl

use warnings;
use strict;
use File::Basename;

my $prog_name = basename $0;

# Keeping it simple...
die "Usage: $prog_name <start_hex> <end_hex>\n" unless @ARGV == 2;

my ($start_hex, $end_hex) = @ARGV;

my $start_dec = hex $start_hex;
my $end_dec   = hex $end_hex;

if ($start_dec > $end_dec) {
    
    print STDERR "Error: Start hex ($start_hex) larger than end hex ($end_hex)\n";
    print STDERR "Start decimal: $start_dec -- end decimal: $end_dec\n";
    exit 1
    
}

for my $decimal ($start_dec..$end_dec) {
    
    printf '%x%s', $decimal, "\n";
    
}