Olá galera, nesta Quick Tips, irei mostra como podemos converter uma String para Byte e de Byte para String, utilizando o Delphi, vamos construir nosso exemplo:

Adicionaremos no Formulário:

2 – TButton

1 – TMemo

1 – TLabeledEdit

Vamos agora a implementação deste exemplo na Unit, salve esta como uFrmPrincipal.pas

 unit uFrmPrincipal;

interface

uses

    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

    Dialogs, DateUtils, StdCtrls, Buttons, ExtCtrls;

type

  { Observe a criação de dois 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

{ Observe as duas funções para a conversão criadas } 

        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.

 

Veja como desenvolvi o nosso formulário.

 


Ao clicarmos em um dos botões poderemos ver o resultado dentro do Memo1 e também no ShowMessage, veja na imagem abaixo :


Este dois exemplos são bem práticos usando a função StrToByte e ByteToStr, podemos fazer as conversões sem nenhum problema.

 

Fico por aqui ate à próxima Quick Tips.

Um abraço 

Wesley Y

wesley@lithic.com.br