program BitManipulation;
// Prints the 8-bit binary representation of an integer
procedure PrintBinary(value: LongInt);
var
i: Integer;
begin
for i := 7 downto 0 do
Write((value shr i) and 1);
Writeln;
end;
// Swaps odd and even bits in a 32-bit integer
function SwapOddAndEvenBits(n: LongInt): LongInt;
var
oddBits, evenBits: LongInt;
begin
// (binary: 101010...) to isolate odd bits
oddBits := n and $AAAAAAAA;
// (binary: 010101...) to isolate even bits
evenBits := n and $55555555;
Write('oddBits: ');
PrintBinary(oddBits);
Write('evenBits: ');
PrintBinary(evenBits);
// Right-shift odd bits by 1 to move them to even positions
oddBits := oddBits shr 1;
// Left-shift even bits by 1 to move them to odd positions
evenBits := evenBits shl 1;
Write('oddBits Right-shift: ');
PrintBinary(oddBits);
Write('evenBits Left-shift: ');
PrintBinary(evenBits);
// Combine shifted bits
SwapOddAndEvenBits := oddBits or evenBits;
end;
var
n: Integer;
result: LongInt;
begin
n := 90;
// Original number in binary
PrintBinary(n);
result := SwapOddAndEvenBits(n);
// Final result in binary
PrintBinary(result);
end.
(*
run:
01011010
oddBits: 00001010
evenBits: 01010000
oddBits Right-shift: 00000101
evenBits Left-shift: 10100000
10100101
*)