Better ways to do this?
Author Message
Better ways to do this?

I was recently asked how to convert a range (a splice) of an array of
binary data into hex format.

The data looks something like this

# 10111010 in msb format
# So the array in natural representation is ordered least significant
bit to most significant bit, but we want msb to lsb.

# We also only want (for arguments sake) bits 2 - 5 (It will always be a
range)
# 10[1110]10 or 1110

The result should be a scalar hex value.

i.e. For the above example
'e' or '0xe'

The following are my solutions. The first 5 address the problem of
lsb->msb to msb->lsb. The final three are concerned with getting the hex
value. Anybody got a cheaper/better way of doing this? BTW I think my
best is Solution #8. As all ways there is more than one way to do it.

# Through out I'll be using the variables \$msb and \$lsb, "Most
Significant

# arbitrary length array of 1's or 0's i.e. the data for a *full* bus.
# Consider these are defined elsewhere in the proper scope, etc., etc.

# Then we maybe have something as simple and straight forward as ...
# Solution #1
my \$bus = "";
for (my \$i = \$msb; \$i >= \$lsb; \$i--) {
\$bus .= \$array[\$i];

Quote:
}

__END__

# Or .. (being a little cute) gives
# Soulution #2
foreach \$i (reverse \$lsb .. \$msb) {
\$bus .= \$array[\$i];

Quote:
}

__END__

# Or yet another way

__END__

# Even simpler (The way I'd probably do it)
# Solution #4

__END__

# but a way, way much more complex, not suggested way
# Solution #5
my \$bus = {

Quote:
};

print &{\$bus->{m2l}}(\$msb,\$lsb);
__END__

# Solution #6
# For hex numbers
# Get binary representation
my \$hexnum = ""

# Get decimal representation

\$hexnum = \$hexnum * 2 + \$_;

Quote:
}

# Get hex representation
\$hexnum = sprintf "%lx", \$hexnum *= 2 ** \$lsb;
__END__

# Compact that a little and you get
# Solution #7
# Get binary representation
my \$hexnum = ""

# Get decimal representation

\$hexnum = \$hexnum * 2 + \$_;

Quote:
}

# Get hex representation
\$hexnum = sprintf "%lx", \$hexnum *= 2 ** \$lsb;
__END__

# Solution #8
# But my personal favorite ...
# Lots of hand waving ... ... ...

\$msb]));
__END__

Fri, 30 Mar 2001 03:00:00 GMT
Better ways to do this?
The best help I can give you is to lead you to the standard Benchmark
module, which will give you quantitative reasons to prefer one
algorithm over another.

\$ perldoc Benchmark

--

http://pobox.com/~jdf

Sun, 01 Apr 2001 03:00:00 GMT

 Page 1 of 1 [ 2 post ]

Relevant Pages