String to Byte and Byte to String: Delphi
In this Quick Tips will show how we can convert a String to Byte and Byte to String using Delphi.
Hello everybody in this "Quick Tips" will show how we can convert a String to Byte and Byte to String using Delphi. We’ll go to build our example:
Add to Form:
2 – TButton
1 – TMemo
1 – TLabeledEdit
We are now going to implement this example in the Unit. Save this as uFrmPrincipal.pas:
uFrmPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DateUtils, StdCtrls, Buttons, ExtCtrls;
type
{ Note the creation of two arrays }
TByteArr = array of byte;
TStringArr = array of String;
TFrmStringToByte = class(TForm)
BitBtn2: TBitBtn;
Memo1: TMemo;
LabeledEdit1: TLabeledEdit;
BitBtn1: TBitBtn;
procedure BitBtn2Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
{ Note the two functions created for the conversion }
function StrToByte(const Value: String): TByteArr;
function ByteToString(const Value: TByteArr): String;
{ Private declarations }
public
{ Public declarations }
end;
var
FrmStringToByte: TFrmStringToByte;
implementation
{$R *.dfm}
function TFrmStringToByte.StrToByte(const Value: String): TByteArr;
var
I: integer;
begin
SetLength(Result, Length(Value));
for I := 0 to Length(Value) - 1 do
Result[I] := ord(Value[I + 1]) – 48;
end;
function TFrmStringToByte.ByteToString(const Value: TByteArr): String;
var
I: integer;
S : String;
Letra: char;
begin
S := '';
for I := Length(Value)-1 Downto 0 do
begin
letra := Chr(Value[I] + 48);
S := letra + S;
end;
Result := S;
end;
procedure TFrmStringToByte.BitBtn1Click(Sender: TObject);
Var
ArByte : TByteArr;
I : Integer;
begin
SetLength(ArByte, Memo1.Lines.Count);
for I := 0 to Memo1.Lines.Count - 1 do
ArByte[I] := StrToInt(Memo1.Lines.Strings[I]);
ShowMessage(ByteToString(ArByte));
end;
procedure TFrmStringToByte.BitBtn2Click(Sender: TObject);
Var
xByte: TByteArr;
I: integer;
begin
Memo1.Clear;
xByte := StrToByte(LabeledEdit1.Text);
for I := 0 to Length(xByte) - 1 do
Memo1.Lines.Add(IntToStr(xByte[I]));
end;
end.
Take a look at the form:
Clicking one of the buttons you can see the result within the “Memo1” and also in “ShowMessage” see in the image below:
These two examples are practical. Using the functions “StrToByte” and “ByteToStr” we can do the conversions without any problem.
Until next Quick Tips.
Wesley Y
wyamazack@rwsolution.com.br
Add your comment
[Fechar]
Este post é fechado - você precisa ter acesso ao post para incluir um comentário.
no comments have been posted - be the first!
Help us to improve! Give us your feedback: