Delphi TBytes型別及與AnsiString、UnicodeString之間的轉換
阿新 • • 發佈:2022-03-14
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 更新時間: