home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.perl
- Path: sparky!uunet!ferkel.ucsb.edu!taco!gatech!paladin.american.edu!howland.reston.ans.net!usc!rpi!batcomputer!cornell!uw-beaver!news.tek.com!psgrain!m2xenix!agora!merlyn
- From: merlyn@ora.com (Randal L. Schwartz)
- Subject: Re: How to convert string to hex?
- In-Reply-To: gweil@ibeam.intel.com's message of Tue, 26 Jan 1993 00:59:02 GMT
- Message-ID: <MERLYN.93Jan27080255@agora.rain.com>
- Sender: merlyn@agora.rain.com (Randal L. Schwartz)
- Organization: Stonehenge Consulting Services; Portland, Oregon, USA
- References: <C1FnMG.AMB@ibeam.intel.com> <C1Fs2F.BB3@ibeam.intel.com>
- Date: Wed, 27 Jan 1993 16:02:55 GMT
- Lines: 35
-
- >>>>> In article <C1Fs2F.BB3@ibeam.intel.com>, gweil@ibeam.intel.com (Garry Weil) writes:
-
- Garry> The best I have come up with, so far is the following:
-
- Garry> #!/usr/local/bin/perl
- Garry> while (<>) {
- Garry> $_ = reverse $_ ;
- Garry> for ($i=1; $i < length($_);) {
- Garry> $c = chop ;
- Garry> printf "0X%x", ord $c ;
- Garry> printf ", " unless $i == length ($_) ;
- Garry> }
- Garry> }
- Garry> print "\n" ;
-
- Garry> Is there something better?
-
- You're not "thinking Perl" yet. You're thinking C, and translating to
- Perl. Here's my cut at it:
-
- #!/usr/sbin/perl :-)
- while (<>) {
- $_ = unpack("H*", $_); # convert each char to 2 hex nybbles
- tr/a-z/A-Z/; # hex generates lowercase
- s/../0X$&, /g; # surround each two chars with human stuff
- s/, $/\n/; # patch up final comma
- print;
- }
-
- ## a long one-liner
- $_ = "0X4A, 0X75, 0X73, 0X74, 0X20, 0X61, 0X6E, 0X6F, 0X74, 0X68, 0X65, 0X72, 0X20, 0X50, 0X65, 0X72, 0X6C, 0X20, 0X68, 0X61, 0X63, 0X6B, 0X65, 0X72, 0X2C"; s/0X(..)/print pack("H*",$1)/eg;
- --
- Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
- merlyn@ora.com (semi-permanent) merlyn@agora.rain.com (for newsreading only)
- phrase: "Welcome to Portland, Oregon ... home of the California Raisins!"
-