_dodger opened this issue on May 08, 2003 ยท 34 posts
_dodger posted Thu, 08 May 2003 at 9:46 PM
Actually, here -- this should explain why I'm a Perl programmer and not a Java programmer, in case that was the real question... the following is a repost from comp.lang.perl
Subject: Re: byte array in perl, how? pack, unpack? java to perl
From: "John W. Krahn" <*****@***.org>
Newsgroups: comp.lang.perl.misc
vientoloco wrote:
>
> This funtions are in java.
> I'll try to find similar functions in perl.
> Help, please :)
> Any tutorial?
>
> /**
> * transforms a hexadecimal string to a byte array
> * @return the byte array, or null if the passed String is null
> * @exception IllegalArgumentException if the passed String is not
> haxadecimal encoded */
In perl you usually don't work with byte arrays but with strings.
> public static byte[] fromHex(String hex) {
sub fromHex {
my $hex = $_[0];
> if (hex == null) {
> return null;
> }
return unless length $hex;
> else if ((hex.length() % 2) != 0) {
> throw new IllegalArgumentException("Hex String length must be a
> multiple of 2.");
> }
die "Hex String length must be a multiple of 2.n" if length $hex %
2;
> int length = hex.length() / 2;
> byte[] result = new byte[length];
> String hits = "0123456789ABCDEF";
> String h = hex.toUpperCase();
>
> for (int i = 0; i < length; i++) {
> char c = h.charAt(2 * i);
> int index = hits.indexOf(c);
> if (index == -1) {
> throw new IllegalArgumentException("Hex String can't contain '"
> + c +"'");
> }
>
> int j = 16 * index;
> c = h.charAt((2 * i) + 1);
> index = hits.indexOf(c);
> if (index == -1) {
> throw new IllegalArgumentException("Hex String can't contain '"
> + c +"'");
> }
die "Hex String can't contain '$1'" if $hex =~ /([^[:xdigit:]])/;
<i><b>[Will you look at that!??]</b></i>
> j += index;
>
> result[i] = (byte) (j & 0xFF); }
$hex =~ s/([[:xdigit:]]{2})/chr hex $1/ge;
> return result;
if ( wantarray ) {
return split //, $hex;
}
else {
return $hex;
}
> }
John
--
use Perl;
program
fulfillment