home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / perl / 8024 < prev    next >
Encoding:
Text File  |  1993-01-28  |  1.8 KB  |  48 lines

  1. Newsgroups: comp.lang.perl
  2. 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
  3. From: merlyn@ora.com (Randal L. Schwartz)
  4. Subject: Re: How to convert string to hex?
  5. In-Reply-To: gweil@ibeam.intel.com's message of Tue, 26 Jan 1993 00:59:02 GMT
  6. Message-ID: <MERLYN.93Jan27080255@agora.rain.com>
  7. Sender: merlyn@agora.rain.com (Randal L. Schwartz)
  8. Organization: Stonehenge Consulting Services; Portland, Oregon, USA
  9. References: <C1FnMG.AMB@ibeam.intel.com> <C1Fs2F.BB3@ibeam.intel.com>
  10. Date: Wed, 27 Jan 1993 16:02:55 GMT
  11. Lines: 35
  12.  
  13. >>>>> In article <C1Fs2F.BB3@ibeam.intel.com>, gweil@ibeam.intel.com (Garry Weil) writes:
  14.  
  15. Garry> The best I have come up with, so far is the following:
  16.  
  17. Garry> #!/usr/local/bin/perl
  18. Garry> while (<>) {
  19. Garry>     $_ = reverse $_ ;
  20. Garry>     for ($i=1; $i < length($_);) {
  21. Garry>         $c = chop ;
  22. Garry>         printf "0X%x", ord $c ;
  23. Garry>         printf ", " unless $i == length ($_) ;
  24. Garry>     }
  25. Garry> }
  26. Garry> print "\n" ;
  27.  
  28. Garry> Is there something better?
  29.  
  30. You're not "thinking Perl" yet.  You're thinking C, and translating to
  31. Perl.  Here's my cut at it:
  32.  
  33. #!/usr/sbin/perl :-)
  34. while (<>) {
  35.     $_ = unpack("H*", $_); # convert each char to 2 hex nybbles
  36.     tr/a-z/A-Z/; # hex generates lowercase
  37.     s/../0X$&, /g; # surround each two chars with human stuff
  38.     s/, $/\n/; # patch up final comma
  39.     print;
  40. }
  41.  
  42. ## a long one-liner
  43. $_ = "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;
  44. -- 
  45. Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
  46. merlyn@ora.com (semi-permanent) merlyn@agora.rain.com (for newsreading only)
  47. phrase: "Welcome to Portland, Oregon ... home of the California Raisins!"
  48.