Showing posts with label delphi byte dyn array. Show all posts
Showing posts with label delphi byte dyn array. Show all posts

Thursday, March 21, 2019

Delphi converting TByteDynArray to string and string to TByteDynArray functions

Delphi converting TByteDynArray to string and string to TByteDynArray functions

function ByteArrayToString(const ByteArray: TByteDynArray): string; var MStream: TMemoryStream; begin MStream := TMemoryStream.Create; CopyToStream(ByteArray, MStream); MStream.Position := 0; try MStream.Read(result,MStream.Size); finally MStream.Free; end; end;


function StringToByteArray(const Str: string): TByteDynArray; var MSTream: TMemoryStream; pTemp: pointer; begin MStream := TMemoryStream.Create; MStream.Write(str,length(str)); MStream.Position := 0; SetLength(Result, MStream.Size); pTemp := @Result[0]; MStream.Position := 0; MStream.Read(pTemp^, MStream.Size); MStream.Free; end;


The same way you can save it in file too.

procedure ByteArrayToFile( const ByteArray : TByteDynArray; const FileName : string ); var Count : integer; F : FIle of Byte; pTemp : Pointer; begin AssignFile( F, FileName ); Rewrite(F); try Count := Length( ByteArray ); pTemp := @ByteArray[0]; BlockWrite(F, pTemp^, Count ); finally CloseFile( F ); end; end;


function FileToByteArray( const FileName : string ) : TByteDynArray; const BLOCK_SIZE=1024; var BytesRead, BytesToWrite, Count : integer; F : FIle of Byte; pTemp : Pointer; begin AssignFile( F, FileName ); Reset(F); try Count := FileSize( F ); SetLength(Result, Count ); pTemp := @Result[0]; BytesRead := BLOCK_SIZE; while (BytesRead = BLOCK_SIZE ) do begin BytesToWrite := Min(Count, BLOCK_SIZE); BlockRead(F, pTemp^, BytesToWrite , BytesRead ); pTemp := Pointer(LongInt(pTemp) + BLOCK_SIZE); Count := Count-BytesRead; end; finally CloseFile( F ); end; end;

Same achieve using Stream,

function ByteArrayFromStream( inStream : TMemoryStream ) : TByteDynArray;
var pTemp : pointer;
begin
  SetLength(Result, inStream.Size );
  pTemp := @Result[0];
  inStream.Position := 0;
  inStream.Read(pTemp^, inStream.Size);
end;

procedure CopyToStream( const InArray : TByteDynArray ; outStream :
TStream );
var pTemp : Pointer;
begin
  pTemp := @InArray[0];
  outStream.Write( pTemp^, Length(InArray));

end;



Delphi Thread Example

Delphi Thread Example Threads mean a lot with the latest computer technology. They allow you to perform multiple tasks at the same time ...