info ihaleden
info ihaleden

Reputation: 63

Get string byte length in delphi

I want to find string byte length. Firstly convert to byte and then get the length so How can i get string byte length?

var
  val : String;
begin
  val:= 'example';
  ShowMessage(IntToStr(Length(val) * ???)); -> BYTE LENGTH
end;

Upvotes: 3

Views: 8904

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598114

You can use the SysUtils.ByteLength() function:

uses
  SysUtils;

var
  val : String;
begin
  val:= 'example';
  ShowMessage(IntToStr(ByteLength(val)));
end;

Just know that ByteLength() only accepts a UnicodeString as input, so any string passed to it, whether that be a (Ansi|Wide|UTF8|RawByte|Unicode)String, will be converted to UTF-16 (if not already) and it will then return the byte count in UTF-16, as simply Length(val) * SizeOf(WideChar).

If you want the byte length of a UnicodeString in another charset, you can use the SysUtils.TEncoding class for that:

var
  val : String;
begin
  val := 'example';
  ShowMessage(IntToStr(TEncoding.UTF8.GetByteCount(val)));
end;

var
  val : String;
  enc : TEncoding;
begin
  val := 'example';
  enc := TEncoding.GetEncoding(...); // codepage number or charset name
  try
    ShowMessage(IntToStr(enc.GetByteCount(val)));
  finally
    enc.Free;
  end;
end;

Or, you can use the AnsiString(N) type to convert a UnicodeString to a specific codepage and then use Length() to get its byte length regardless of what N actually is:

type
  Latin1String = type AnsiString(28591); // can be any codepage supported by the OS...
var
  val : String;
  val2: Latin1String;
begin
  val := 'example';
  val2 := Latin1String(val);
  ShowMessage(IntToStr(Length(val2)));
end;

Upvotes: 8

Kromster
Kromster

Reputation: 7437

var
  val : String;
begin
  val:= 'example';
  ShowMessage(IntToStr(Length(val) * SizeOf(Char)));
end;

Or use ByteLength to obtain the size of a string in bytes. ByteLength calculates the size of the string by multiplying the number of characters in that string to the size of a character.

Upvotes: 4

Related Questions