How to use XOR to swap two characters in a string in Pascal

1 Answer

0 votes
program XorSwapProgram;

{$mode objfpc}{$H+}

uses
  SysUtils;

(**
 * Swaps two characters in a string using the XOR swap algorithm.
 *
 * This procedure demonstrates XOR swapping for educational purposes.
 * In production code, prefer using a temporary variable or System.Swap()
 * for clarity and optimizer safety.
 *
 * @param Text  String containing the characters to swap (passed by reference).
 * @param Left  1-based index of the first character.
 * @param Right 1-based index of the second character.
 *)
procedure XorSwapCharacters(var Text: string; Left, Right: SizeInt);
begin
  // Boundary check (Free Pascal strings are 1-indexed)
  if (Text = '') or (Left < 1) or (Right < 1) or 
     (Left > Length(Text)) or (Right > Length(Text)) then
    Exit;

  // XOR swap fails if Left = Right because (X xor X) yields 0
  if Left = Right then
    Exit;

  // Perform bitwise XOR swap using ordinal ASCII values
  Text[Left]  := Char(Ord(Text[Left])  xor Ord(Text[Right]));
  Text[Right] := Char(Ord(Text[Right]) xor Ord(Text[Left]));
  Text[Left]  := Char(Ord(Text[Left])  xor Ord(Text[Right]));
end;

var
  Text: string;
begin
  Text := 'hello';

  WriteLn('Before: ', Text);

  // 1-based indexing: index 2 ('e') and index 5 ('o')
  XorSwapCharacters(Text, 2, 5);

  WriteLn('After:  ', Text);
end.


{
run:

Before: hello
After:  holle

}

 



answered Sep 29 by avibootz
...