Delphi TBytes类型及与AnsiString、UnicodeString之间的转换


Delphi TBytes类型及与AnsiString、UnicodeString之间的转换

1、TBytes类型(引用单元:System.SysUtils)

type
  TArray = array of T;  
  TBytes = TArray;

故 TBytes 类型,可以看成是 array of Byte  

2、UnicodeString与TBytes的相互转换

function TEncoding.GetBytes(const S: string): TBytes;
var
  Len: Integer;
begin
  Len := GetByteCount(S);
  SetLength(Result, Len);
  GetBytes(S, Low(S), Length(S), Result, 0, Low(S));
end;

function BytesOf(const Val: UnicodeString): TBytes;
begin
  Result := TEncoding.Default.GetBytes(Val);
end;

function StringOf(const Bytes: TBytes): UnicodeString;
begin
  if Assigned(Bytes) then
    Result := TEncoding.Default.GetString(Bytes, Low(Bytes), High(Bytes) + 1)
  else
    Result := '';
end;

function TEncoding.GetString(const Bytes: TBytes): string;
begin
  Result := GetString(Bytes, 0, Length(Bytes));
end;

function TEncoding.GetString(const Bytes: TBytes; ByteIndex, ByteCount: Integer): string;
var
  Len: Integer;
begin
  if (Length(Bytes) = 0) and (ByteCount <> 0) then
    raise EEncodingError.CreateRes(@SInvalidSourceArray);
  if ByteIndex < 0 then
    raise EEncodingError.CreateResFmt(@SByteIndexOutOfBounds, [ByteIndex]);
  if ByteCount < 0 then
    raise EEncodingError.CreateResFmt(@SInvalidCharCount, [ByteCount]);
  if (Length(Bytes) - ByteIndex) < ByteCount then
    raise EEncodingError.CreateResFmt(@SInvalidCharCount, [ByteCount]);

  Len := GetCharCount(Bytes, ByteIndex, ByteCount);
  if (ByteCount > 0) and (Len = 0) then
    raise EEncodingError.CreateRes(@SNoMappingForUnicodeCharacter);
  SetLength(Result, Len);
  GetChars(@Bytes[ByteIndex], ByteCount, PChar(Result), Len);
end;

function TEncoding.GetString(const Bytes: array of Byte): string;
var
  Len: Integer;
begin
  Len := GetCharCount(@Bytes[0], Length(Bytes));
  if (Length(Bytes) > 0) and (Len = 0) then
    raise EEncodingError.CreateRes(@SNoMappingForUnicodeCharacter);
  SetLength(Result, Len);
  GetChars(@Bytes[0], Length(Bytes), PChar(Result), Len);
end;

其他相关

{$IFNDEF NEXTGEN}
function BytesOf(const Val: RawByteString): TBytes;
var
  Len: Integer;
begin
  Len := Length(Val);
  SetLength(Result, Len);
  Move(Val[1], Result[0], Len);
end;

function BytesOf(const Val: AnsiChar): TBytes;
begin
  SetLength(Result, 1);
  Result[0] := Byte(Val);
end;

function BytesOf(const Val: WideChar): TBytes;
begin
  Result := BytesOf(UnicodeString(Val));
end;
{$ENDIF}

3、AnsiString 与 TBytes 的相互转换

function BytesOf(const Val: AnsiString): TBytes;     
var
  Len: Integer;
begin
  Len := Length(Val);
  SetLength(Result, Len);
  Move(Val[1], Result[0], Len);
end;

function StringOf(const buf:TBytes): AnsiString;
begin
  SetLength(Result, Length(buf));
  CopyMemory(PAnsiChar(result), @buf[0], Length(buf));
end;

  

创建时间:2022.03.14  更新时间:

相关