Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well here's a option that would do the conversion as fast as I can think of.</p> <p>Features of the code:</p> <ul> <li>Only one allocation for the string (so no realloc and no move or copy)</li> <li>Fast read from the file.</li> </ul> <p>Since we know that one byte translates to exactly two hexadecimal chars, we know our result string needs to be exactly twice the size of the file. We allocate an string of the required size and then we read from the file in large-enough blocks so the OS can optimize it for us (reading byte-by-byte is evil). We use an actual string but we write into the string using an pointer:</p> <pre><code>function TEditorDeschidereDeCredite.FileToHex(FileName: string): AnsiString; var FS:TFileStream; PS:PAnsiChar; Block:array[0..1023] of byte; // 1Kb len,i,pos:Integer; B:Byte; const Nibbs: array[0..15] of AnsiChar = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); begin FS := TFileStream.Create(FileName, fmOpenRead); try Result := ''; SetLength(Result, FS.Size * 2); PS := PAnsiChar(Result); pos := 0; // position into the result string len := FS.Read(Block, SizeOf(Block)); while len &lt;&gt; 0 do begin for i:=0 to len-1 do begin B := Block[i]; PS[pos] := Nibbs[B div $F]; Inc(pos); PS[pos] := Nibbs[B mod $F]; Inc(pos); end; len := FS.Read(Block, SizeOf(Block)); end; finally FS.Free; end; end; </code></pre> <p>P.S: I'm using AnsiString, and PAnsiChar so the code works also works with Unicode Delphi. If you happen to be on Delphi 2010 find a way to use this in it's current form (AnsiString) so you can skip the conversions.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload