DelphiTBytes类型及与AnsiString、UnicodeString之间的转换
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
DelphiTBytes类型及与AnsiString、UnicodeString之间的转换Delphi TBytes类型及与AnsiString、UnicodeString之间的转换
1、TBytes类型(引⽤单元:System.SysUtils)
type
TArray<T> = array of T;
TBytes = TArray<Byte>;
故 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 更新时间:。