Skip to content

Instantly share code, notes, and snippets.

@JensMertelmeyer
Created February 25, 2020 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JensMertelmeyer/5987a6430d8da2d0ca1297748f61c91b to your computer and use it in GitHub Desktop.
Save JensMertelmeyer/5987a6430d8da2d0ca1297748f61c91b to your computer and use it in GitHub Desktop.
Helper.Endianess.pas
unit Helper.Endianess;
interface
type
TEndianHelper = class
protected const
stdAlsoFlipBytes = False;
public
class procedure WordFlip(var Value: Word);
class function WordFlipped(const Value: Word): Word;
class procedure DWordFlip(var Value: LongWord; const alsoFlipBytes: Boolean = stdAlsoFlipBytes);
class function DWordFlipped(const Value: Longword; const alsoFlipBytes: Boolean = stdAlsoFlipBytes): LongWord;
end;
implementation
type
TWordHelper = record helper for System.Word
/// <summary>
/// Vertauscht beide Bytes
/// </summary>
public procedure flipEndianess();
end;
TCardinalHelper = record helper for System.Cardinal
/// <summary>
/// Vertauscht beide Words
/// </summary>
public procedure flipEndianess(const alsoFlipBytes: Boolean = False);
end;
{ TWordHelper }
procedure TWordHelper.flipEndianess();
var
firstBytePtr, secondBytePtr: PByte;
firstByteValue: Byte;
begin
firstBytePtr := Addr(self);
secondBytePtr := firstBytePtr + 1;
firstByteValue := firstBytePtr^;
firstBytePtr^ := secondBytePtr^;
secondBytePtr^ := firstByteValue;
end;
{ TCardinalHelper }
procedure TCardinalHelper.flipEndianess(const alsoFlipBytes: Boolean);
var
firstWordPtr, secondWordPtr: PWord;
firstWordValue: Word;
begin
firstWordPtr := Addr(self);
secondWordPtr := firstWordPtr; Inc(secondWordPtr);
firstWordValue := firstWordPtr^;
firstWordPtr^ := secondWordPtr^;
secondWordPtr^ := firstWordValue;
if alsoFlipBytes then begin
firstWordPtr^.flipEndianess();
secondWordPtr^.flipEndianess();
end;
end;
{ TEndianHelper }
class procedure TEndianHelper.DWordFlip(
var Value: LongWord;
const alsoFlipBytes: Boolean
);
begin
Value.flipEndianess(alsoFlipBytes);
end;
class function TEndianHelper.DWordFlipped(
const Value: Longword;
const alsoFlipBytes: Boolean
): LongWord;
begin
Result := Value;
Result.flipEndianess(alsoFlipBytes);
end;
class procedure TEndianHelper.WordFlip(var Value: Word);
begin
Value.flipEndianess();
end;
class function TEndianHelper.WordFlipped(const Value: Word): Word;
begin
Result := Value;
Result.flipEndianess();
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment