On Fri, 13 Jan 2012 16:51:31 -0800 (PST), battles
Post by battlesI am converting a string of incoming characters that represent a hex
var CharStr: string;
const HexStringRep : string = '616263';
CharStr := char(strtoint('$' + HexStringRep[1] + HexStringRep[2])) +
char(strtoint('$' + HexStringRep[3] +
HexStringRep[4])) +
char(strtoint('$' + HexStringRep[5] +
HexStringRep[6]))...
This works ok, but I was wondering if there is a fancier way of doing
this?
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms,
Dialogs, ExtCtrls, StdCtrls, StrUtils;
type
TfrmMain = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Splitter1: TSplitter;
Panel1: TPanel;
btnHexToString: TButton;
btnStringToHex: TButton;
btnClearAll: TButton;
procedure btnHexToStringClick(Sender: TObject);
procedure btnClearAllClick(Sender: TObject);
procedure btnStringToHexClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function HexToString(Hexy: string): string;
function StripJunk(Junk: string): string;
function StringToHex(Stringy: string): string;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
//--------------------------------------------------
function TfrmMain.HexToString(Hexy: string): string;
var
i: Integer;
begin
Result:= '';
for i := 1 to length(Hexy) div 2 do
Result:= Result + Char(StrToInt('$' + Copy(Hexy,(I-1)*2+1,2)));
end;
//------------------------------------------------
function TfrmMain.StripJunk(Junk: string): string;
var
JunkSpace, JunkComma: string;
begin
JunkSpace := AnsiReplaceStr(Junk,' ','');
JunkComma := AnsiReplaceStr(JunkSpace,',','');
Result := HexToString(JunkComma);
Memo2.Lines.Append(Result);
end;
//-----------------------------------------------------
function TfrmMain.StringToHex(Stringy: string): string;
var
i, i2: Integer;
s: string;
begin
i2 := 1;
for i := 1 to Length(Stringy) do
begin
Inc(i2);
if i2 = 2 then
begin
s := s + ' ';
i2 := 1;
end;
s := s + IntToHex(Ord(Stringy[i]), 2);
end;
Result := s;
end;
//------------------------------------------------------
procedure TfrmMain.btnHexToStringClick(Sender: TObject);
var
x: integer;
begin
for x := 0 to Memo1.Lines.Count -1 do
begin
StripJunk(Memo1.Lines[x]);
end;
end;
//------------------------------------------------
procedure TfrmMain.btnClearAllClick(Sender: TObject);
begin
Memo1.Clear;
Memo2.Clear;
end;
//------------------------------------------------------
procedure TfrmMain.btnStringToHexClick(Sender: TObject);
var
x: integer;
begin
for x := 0 to Memo1.Lines.Count -1 do
Memo2.Lines.Append(StringToHex(Memo1.Lines[x]));
end;
end.