This represents my first effort with Perl/TK. The basic idea behind this was to create a GUI app that would quickly convert hex values to char and vice versa without having to rely on eyeing an ASCII table each time I want to perform a conversion. For example, this app will take the following HEX values
50 65 72 6C 20 4D 6F 6E 6B 73 21
and output...well, you'll just have to see. ;)
This application can also be used in some cases to create or convert Snort IDS bytecode, which could prove useful when working with signatures.
#!c:/perl/bin/perl -w use Tk; use Tk::DialogBox; use strict; sub convert_hex; sub convert_char; my $main = new MainWindow(-title => 'Hex2Char - Char2Hex'); my (@splithex, @splitchar); my ($val, $value); my $leftframe = $main->Frame(); $leftframe->pack(-side => 'left'); my $rightframe = $main->Frame(); $rightframe->pack(-side => 'right'); $leftframe->Label(-text => "Hex")->pack(); my $hexval = $leftframe->Entry(-width => '30')->pack(); my $buttonleft = $leftframe->Button(-text => '>>', -command => sub{convert_hex;})->pack(); $rightframe->Label(-text => "Char")->pack(); my $charval = $rightframe->Entry(-width => '30')->pack();; my $buttonright = $rightframe->Button(-text => '<<', -command => sub{convert_char;})->pack(); my $exit = $main->Button(-text => 'Exit', -command => sub{exit;}); $exit->pack(-side => 'bottom'); MainLoop; sub convert_hex { my @charconv = (); my $hexvals = $hexval->get; @splithex = split(' ', $hexvals); foreach $value (@splithex) { $val = pack "H*", $value; push @charconv, "$val"; } my @switch = reverse @charconv; $charval->delete(0, 'end'); map {$charval->insert(0,$_)} @switch; } sub convert_char { my @hexconv = (); my $charvals = $charval->get; @splitchar = split(//, $charvals); foreach $value (@splitchar) { $val = unpack "H*", $value; push @hexconv, "$val "; } my @switch = reverse @hexconv; $hexval->delete(0, 'end'); map {$hexval->insert(0,uc $_)} @switch; }
As always, comments and suggestions for improvement welcome.

cheers, -semio

Replies are listed 'Best First'.
(jeffa) Re: Perl/TK hex2char - char2hex convertor
by jeffa (Bishop) on Aug 25, 2002 at 00:36 UTC
    I like it, but i do have a couple of suggestions:

    First, please pick an indentation style and stick with it. Check out perltidy.

    Second, you are using foreach where you should be using map, and you are using map where you should be using foreach (or for). Try this instead:
    sub convert_hex { my @charconv = map { pack "H*", $_ } split(/\s/, $hexval->get); $charval->delete(0, 'end'); $charval->insert(0, $_) for reverse @charconv; } sub convert_char { my @hexconv = map { unpack "H*", $_ } split(//, $charval->get); $hexval->delete(0, 'end'); $hexval->insert(0, $_) for reverse @hexconv; }
    Use map when you want to transform one list (array) into another - don't use it in void context, use for (or foreach) instead. Other then that, looks good to me. :)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      I guess I am the only one, but I was not able to successfully run the script. I get a error "Unrecognized character \xAD at test.pl line 4." when I execute it. I am not a Perl programmer but I need to convert a file from hex to chars. Any idea why? Thanks Dan
        This is probably the wrong thread ... check out converting hex to char instead. Also, the following might be more helpful for what you need:
        use strict; use warnings; print char2hex('a'),$/; print hex2char(62),$/; sub char2hex { return sprintf('%x',ord($_[0])); } sub hex2char { return chr(hex($_[0])); }
        Goo luck :)

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)
        
( Wx::HexOrChar ) Re: Perl/TK hex2char - char2hex convertor
by PodMaster (Abbot) on Aug 25, 2002 at 13:32 UTC
    Cheers ;D
    =head1 NAME Wx::HexOrChar - a Wx Dialog/App for converting hex/text to text/hex =head1 SYNOPSIS perl -MWx::HexOrChar -e Wx::HexOrChar::App->new()->MainLoop() # or use Wx::HexOrChar; Wx::HexOrChar::App->new()->MainLoop(); # or even require Wx::HexOrChar; system $^X, $INC{'Wx/HexOrChar.pm'}; # or the oneliner version (quotes may vary ;) perl -mWx::HexOrChar -e"system $^X, $INC{q{Wx/HexOrChar.pm}};" # -m is equivalent to use Wx::HexOrChar(); in case you was wonderi +ng =head1 DESCRIPTION Run it as a standalone app, or embed it easily into any wxPerl application, cause you never know when it might come in handy to convert hex to text, and text to hex. You probably got Wx::HexOrChar from http://perlmonks.com/index.pl?node_id=192667 $Id: HexOrChar.pm,v 1.5 2002/08/25 13:00:26 _ Exp $ =cut package Wx::HexOrChar; use Wx qw( :everything ); use Wx::Event qw( EVT_BUTTON EVT_RIGHT_DOWN ); use base qw( Wx::Frame ); use vars qw( $VERSION ); use strict; $VERSION = 0.01; sub new { my $class = shift; my $SIZE = [400,400]; my $self = $class->SUPER::new( undef, -1, "Wx::HexOrChar - you know what it is ;)", [0,0], $SIZE, wxDEFAULT_FRAME_STYLE | wxCLIP_CHILDREN, # for easy commenting out ); $self->SetIcon( Wx::GetWxPerlIcon() ); my $p = Wx::Panel->new( $self, -1, [50,50], $SIZE, ); $self->GUI($p); ## and we construct the dialog EVT_BUTTON( $self, $self->ID('TO_HEX_BUTTON'), \&OnToHex ); EVT_BUTTON( $self, $self->ID('TO_TEXT_BUTTON'), \&OnToText ); EVT_RIGHT_DOWN( $self, \&OnAbout ); EVT_RIGHT_DOWN( $p, \&OnAbout ); my( $MainSizer ) = Wx::BoxSizer->new( Wx::wxHORIZONTAL ); $MainSizer->Add( $p, 1, wxGROW ); $self->SetSizer( $MainSizer ); $self->SetAutoLayout( 1 ); ## ;) $self->Layout(); ##force layout of the children anew $MainSizer->Fit( $self ); $MainSizer->SetSizeHints( $self ); return $self; } #### THE EVENT HANDLERS sub OnToText { my( $self, $event ) = @_; my $HexString = $self->FindWindow( $self->ID('HEX_STRING') )->GetV +alue(); $HexString = join '', map { pack "H*", $_ } split /\s/, $HexString +; $self->FindWindow( $self->ID('TEXT_STRING') )->SetValue( $HexStrin +g ); } sub OnToHex { my( $self, $event ) = @_; my $TextString = $self->FindWindow( $self->ID('TEXT_STRING') )->Ge +tValue(); $TextString = join' ', map { unpack "H*", $_ } split //, $TextStr +ing; $self->FindWindow( $self->ID('HEX_STRING') )->SetValue( $TextStrin +g ); } sub OnAbout { my( $self, $event ) = @_; # display a simple about box (i just keep copying and pasting this) Wx::MessageBox( qq[ ${\__PACKAGE__} $VERSION Created by podmaster of perlmonks.org fame running on wxPerl $Wx::VERSION ${\wxVERSION_STRING()} This program is released under the same terms as perl itsel +f (if you don't know what that means, visit http://perl.com ) To learn more about wxPerl visit http://wxperl.sf.net/ ], "About ${\__PACKAGE__} $VERSION", # TITLE wxOK | wxICON_INFORMATION, $self ); } ##### GGGUI GENERATORs sub BOXS { my( $self, $parent, $str, $orient ) = @_; return Wx::StaticBoxSizer->new( Wx::StaticBox->new( $parent, -1, $str, ,), $orient, ,); } sub ID { ## ALL KEYS ARE UPPERCASED my($self, $key, $dontCreate ) = @_; return $self->{"\0ID_"} if not defined $key; $self->{"\0I"} ||=6660; # the perpetual ID incrementor $key = uc($key); if(exists $self->{"\0ID_"}->{$key} ) { return $self->{"\0ID_"}->{$key}; } else { return 0 if $dontCreate; return $self->{"\0ID_"}->{$key} = ++$self->{"\0I"}; } } sub TEXS { my( $self, $parent, $id, $init, $poss, $size ) = @_; $poss ||= wxDefaultPosition; $size ||=[400,40]; return Wx::TextCtrl->new( $parent, $self->ID($id), $init, $poss, $size, wxTE_MULTILINE, ,); } sub GUI { my( $self, $parent ) = @_; my( $RootSizer ) = Wx::BoxSizer->new( wxVERTICAL ); my( $HexSizer ) = $self->BOXS($parent, "Hex String", wxHORIZONTAL) +; my( $HexString ) = $self->TEXS($parent, HEX_STRING => "4a 75 73 74 + 20 41 6e 6f 74 68 65 72 20 50 65 72 6c 20 77 48 61 63 6b 65 72",); $HexString->SetToolTip("Type in hex here (or watch it come out her +e)"); $HexSizer->AddWindow( $HexString, 1, wxGROW|wxALIGN_CENTRE, 5,); my( $TextSizer ) = $self->BOXS($parent, "Text String:", wxHORIZONT +AL); my( $TextString ) = $self->TEXS( $parent, TEXT_STRING => 'I am te +xt' ); Wx::ToolTip::Enable(1); Wx::ToolTip::SetDelay(50); # ms $TextString->SetToolTip( 'Type in text here (or watch it come out +here)' ); ## tool tips seem to suck for lables and text controls $TextSizer->Add( $TextString, 1, wxGROW|wxALIGN_CENTER_VERTICAL, 5 + ); my( $ButtonSizer ) = Wx::BoxSizer->new( wxVERTICAL ); my( $ToHexButton ) = Wx::Button->new( $parent, $self->ID('TO_HEX_BUTTON'), "VV", wxDefaultPosition, wxDefaultSize, wxNO_BORDER ); $ToHexButton->SetToolTip("Turn that TEXT above into HEX below"); my( $ToTextButton ) = Wx::Button->new( $parent, $self->ID('TO_TEXT_BUTTON'), "AA", wxDefaultPosition, wxDefaultSize, wxNO_BORDER ); $ToTextButton->SetToolTip("Turn that HEX below into TEXT above"); $ToTextButton->SetDefault(); $ButtonSizer->AddWindow( $ToTextButton, 1, wxALL|wxALIGN_CENTRE, 5 + ); $ButtonSizer->AddWindow( $ToHexButton, 1, wxALL|wxALIGN_CENTRE, 5 +); $RootSizer->Add( $TextSizer, 1, wxGROW | wxALIGN_CENTRE, 5 ); $RootSizer->Add( $ButtonSizer, 0, wxGROW | wxALIGN_CENTRE, 5 ); $RootSizer->Add( $HexSizer, 1, wxGROW | wxALIGN_CENTRE, 5 ); $ToTextButton->SetFocus(); # so if you hit enter, you get mah sig +;) $parent->SetAutoLayout( 1 ); $parent->SetSizer( $RootSizer ); $RootSizer->Fit( $parent ); $RootSizer->SetSizeHints( $parent ); return $RootSizer; } package Wx::HexOrChar::App; use strict; use Wx; use base qw(Wx::App); sub OnInit { my( $self ) = @_; my( $frame ) = new Wx::HexOrChar(); $frame->Show(1); $frame->Refresh(); 1; } package main; # if this file is invoked directly (not use'd), run the app unless( caller() ) { Wx::HexOrChar::App->new()->MainLoop(); } __END__ =head1 AUTHOR podmaster - http://perlmonks.org/index.pl?node=podmaster =head1 LICENSE Copyright D.H ( podmaster ) http://crazyinsomniac.perlmonk.org 2002, All rights reserved. This program is released under the same terms as perl itself (if you don't know what that means, visit http://perl.com ) =cut

    ____________________________________________________
    ** The Third rule of perl club is a statement of fact: pod is sexy.

Re: Perl/TK hex2char - char2hex convertor
by zentara (Cardinal) on Aug 25, 2002 at 17:28 UTC
    In all of these hex-char converters, there is the problem of eye-strain trying to match up the 1 to 1 relationship between the chars and the hex values. (Let's see did I count over 10 chars or was that 11, etc). It's better to display the chars and hex values together, so you can see the match at a glance. Below is some code which does that. If you could do that with your tk script, it would be a great app.
    #!/usr/bin/perl -wnl012 # Prints the contents of a file a line at a time # followed by the ASCII value of each character in vertical columns. # Useful for debugging. # If no filename is specified then input is read from the keyboard. # Version 1.00 Ian Howlett ian@ian-howlett.com 6 July 2001 # Version 1.10 James Yolkowski ajy@sentex.net 8 July 2001 print; # Print the line we've just read @hexvals = map {sprintf "%02X", ord $_} split //; # Get hex value of e +ach char for $a (0, 1) {print map {substr $_, $a, 1} @hexvals} # Print the hex +values. #print "\n";

    Janitored by Arunbear - removed pre tags to improve readability

Re: Perl/TK hex2char - char2hex convertor
by Mr. Muskrat (Canon) on Aug 24, 2002 at 18:01 UTC

    59 6F 75 20 61 72 65 20 4A 75 73 74 20 41 6E 6F 74 68 65 72 20 50 65 72 6C 2F 54 6B 20 48 61 63 6B 65 72 20 3B 29

    Tk is on my list of things to learn.