Monday, March 18, 2013

Ascii-Hex-Ascii Converter code

0 comments
In programming, we need Hexadecimal codes for many reasons. At least Computer Science students need no introduction to the fun of converting to Hex codes. Here is a fun experiment on how to convert ASCII text to Hex code and vice-versa. It is written in Free Pascal and can be easily used in Lazarus (or may be Delphi as well).

This is written as a snippet. So come on, use it how you want to! Use it in a console application or a GUI interface, it will just work.

Function for converting Ascii (String) to Hex:


Function TForm1.StrToHex(s: String): String;
Var
  i: Integer;
  ch: Char;
Begin
  Result:=''; i:=1;
  While i<=Length(s) Do Begin
       ch := s[i];
       Result := Result+IntToHex(ord(ch), 2);
       Inc(i);
  end;

End;

Function to convert Hex to Ascii:


Function TForm1.HexToStr(s: String): String;
Var i: Integer;
Begin
  Result:=''; i:=1;
  While i<Length(s) Do Begin
    Result:=Result+Chr(StrToIntDef('$'+Copy(s,i,2),0));
    Inc(i,2);
  End;
End;

Don't forget to add the declaration at the top of the unit. You may put your cursor on the function name and press Ctrl+Shift+C. This will automatically add the declaration at the top. (But mind the TForm1 part)


Feel free to comment on this snippet if you have some improvements on this code or have found a bug.

Ref:
http://www.lazarus.freepascal.org/index.php?topic=4807.0

Continue reading ...
 

Blogroll

Translate This Blog

Copyright © আদনানের ব্লগ Design by BTDesigner | Blogger Theme by BTDesigner | Powered by Blogger