Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string byte length in delphi

Tags:

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;
like image 304
info ihaleden Avatar asked Mar 12 '26 02:03

info ihaleden


2 Answers

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;
like image 106
Remy Lebeau Avatar answered Mar 14 '26 02:03

Remy Lebeau


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.

like image 23
Kromster Avatar answered Mar 14 '26 01:03

Kromster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!