How do I read hex from a file into a string? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How do I read hex from a file into a string?

thor64thor64 Posts: 2Member
Shall i use read or. Please help?

I want to read a file into a string, that maybe will look like this:
'2090FFFF0000FFEE' etc.

I know how to write (saw a post from Freakboy....)

please help a beginner...


Comments

  • AdamAdam Posts: 21Member
    : Shall i use read or. Please help?
    :
    : I want to read a file into a string, that maybe will look like this:
    : '2090FFFF0000FFEE' etc.
    :
    : I know how to write (saw a post from Freakboy....)
    :
    : please help a beginner...
    :

    I would use stream I/O. The following example will (should anyway) read a complete file into a string of hexadecimal characters:
    [code]
    function LoadFileAsHex(const FileName: String) : String;
    var
    Stream : TFileStream;
    BinStr : String;
    TmpStr : String;
    HexStr : String;
    i : Integer;
    begin
    Stream:= TFileStream.Create(FileName, fmOpenRead);
    try
    SetLength(BinStr, Stream.Size);
    Stream.ReadBuffer(BinStr, Length(BinStr));
    finally
    Stream.Free;
    end;

    SetLength(HexStr, 2*Length(BinStr));
    for i:= 1 to Length(BinStr) do begin
    TmpStr:= Format('%.2x', [BinStr[i]]);
    HexStr[2*i-1]:= TmpStr[1];
    HexStr[2*i]:= TmpStr[2];
    end;

    Result:= HexStr;
    end; {LoadFileAsHex}
    [/code]
    This code is not tested, but it should work. Since this function reads the whole file into memory, it uses a little RAM. For small files, however, it should be fairly quick.

    Using stream I/O, you could also read one byte at a time or some fixed number of bytes at a time. Streams are very flexible, without being quite as low-level as the I/O functions in the Windows API.

    HTH,
    Adam


  • FreakboYFreakboY Posts: 117Member
    I guess u got the answer!


  • thor64thor64 Posts: 2Member
    Thank U ;)

Sign In or Register to comment.