Skip to content

Instantly share code, notes, and snippets.

@DarkCoderSc
Created November 9, 2019 14:49
Show Gist options
  • Save DarkCoderSc/56a832bd43f73024b88cd0db908dc77b to your computer and use it in GitHub Desktop.
Save DarkCoderSc/56a832bd43f73024b88cd0db908dc77b to your computer and use it in GitHub Desktop.
Little code snippet to display buffer from any kind to viewable hex table (little an hex editor). Useful for console debug output.
(*
Jean-Pierre LESUEUR
@DarkCoderSc
https://www.phrozen.io/
Note: This code is a bit old and could be optimized. Feel free to do so ;)
*)
function BufferToHexView(ABuffer : PVOID; ABufferSize : Int64; pLastOffset : PNativeUINT = nil; AStartOffset : NativeUINT = 0) : String;
var ARows : DWORD;
i, n : integer;
AVal : Byte;
sBuilder : TStringBuilder;
HexVal : array[0..16-1] of TVarRec;
AsciiVal : array[0..16-1] of TVarRec;
HexMask : String; {%x}
AsciiMask : String; {%s}
begin
result := '';
///
ARows := ceil(ABufferSize / 16);
sBuilder := TStringBuilder.Create();
try
{
Row
}
for I := 0 to ARows -1 do begin
{
Col
}
for n := 0 to 16-1 do begin
AVal := PByte(NativeUInt(ABuffer) + (I * 16) + n)^;
HexVal[n].VType := vtInteger;
HexVal[n].VInteger := AVal;
AsciiVal[n].VType := vtChar;
if AVal in [32..255] then begin
AsciiVal[n].VChar := AnsiChar(AVal);
end else begin
AsciiVal[n].VChar := '.';
end;
end;
HexMask := '';
AsciiMask := '';
for n := 0 to 16-1 do begin
if ((I * 16) + n) > ABufferSize then begin
HexMask := HexMask + #32#32#32;
AsciiMask := AsciiMask + #32#32;
continue;
end;
HexMask := HexMask + '%.2x' + #32;
AsciiMask := AsciiMask + '%s';
end;
Delete(HexMask, length(HexMask), 1);
{
Draw
}
sBuilder.AppendLine(
Format('%.8x', [AStartOffset + (I * 16)]) + '|' +
Format(HexMask, HexVal) + '|' +
Format(AsciiMask, AsciiVal)
);
end;
finally
result := sBuilder.ToString();
if Assigned(pLastOffset) then begin
pLastOffset^ := (ARows * 16);
end;
sBuilder.Free;
end;
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment