Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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!


Sign In or Register to comment.