Cenk Aybeyaz
Cenk Aybeyaz

Reputation: 165

How can I convert string to hex without changing its length?

I convert string to hex, but when I convert, hex code has 2*length(string) can I do that "string length=hexstring length" is it possible?

I found this code does it work?

var
  fs: TFileStream;
  temp: Char;
  buffer: string;
  pBuffer: PAnsiChar;
  text: PAnsiChar;
begin
  fs := TFileStream.Create('file way', fmOpenRead or fmShareDenyNone);
  fs.Position := 0;
  while fs.Position < fs.Size do
  begin
    fs.Read(temp, 1); //buffer içine her defasında 1 byte gelir.
    buffer := buffer + temp;
  end;
  pBuffer := PAnsiChar(buffer);
  BinToHex(pBuffer, text, Length(buffer));
  Memo1.Text := text;
end;

Upvotes: 0

Views: 600

Answers (1)

paxdiablo
paxdiablo

Reputation: 881293

The only way to do this is to map the characters to 4-bit values somehow and convert that to hex. That will mean only sixteen values are possible so, no, you can't do this in a general way if there are more than sixteen possibilities.

Eight-bit values (or any length from five to eight bits) requires two hex digits per value.

Upvotes: 3

Related Questions