Reputation: 171
Situation: I'm hooking Send() & Recv() from ws2_32, Now I'm trying to convert the data that is contained at the Buffer with the function below. However when I do so, I see some packets are being displayed with 1 nibble (e.g. "CA FE BA BE DE AD CO D") and not 2 hex digits like we would normally see (e.g. "CA FE BA BE DE AD C0 DE").
function ConvertDataToHex(Buffer: Pointer; Length: Word): string;
var
Iterator: Integer;
HexBuffer: string;
C: string;
Counter: Integer;
HexString: string;
begin
HexBuffer := '';
HexString := '';
for Iterator := 0 to Length - 1 do
begin
HexBuffer := HexBuffer +
IntToHex(Ord(char(Pointer(Integer(Buffer) + Iterator)^)), 2);
end;
for C in HexBuffer do
begin
Counter := Counter + 1;
if not Odd(Counter) then
begin
HexString := C + ' ';
end
else
begin
HexString := C;
end;
end;
Result := HexString;
end;
Given the explanation above, do you see some anomaly in the code that could be causing some of the resulting strings to have have an odd length in the string?
Upvotes: 1
Views: 282
Reputation: 612884
Your function returns HexString
which is either a single character, or a single character followed by a string. It certainly does not return what you expect it to return, or even claim that it returns.
The function should go like this:
function ConvertDataToHex(Buffer: Pointer; Len: Integer): string;
var
i: Integer;
P: PByte;
begin
Result := '';
P := Buffer;
for i := 0 to Len-1 do begin
Result := Result + IntToHex(P^, 2);
if i<Len-1 then begin
Result := Result + ' ';
end;
inc(P);
end;
end;
As a simple demonstration, this code
var
foo: Int64 = $0123456789abcdef;
....
Writeln(ConvertDataToHex(@foo, SizeOf(foo)));
results in this output:
EF CD AB 89 67 45 23 01
Upvotes: 4