How to reverse the bits of a number in Pascal

1 Answer

0 votes
program BitReverse;

{$mode objfpc}{$H+}

uses
  SysUtils;

function IntToBin32(n: LongWord): string;
var
  i: Integer;
begin
  SetLength(Result, 32);
  for i := 31 downto 0 do
  begin
    if (n and (1 shl (31 - i))) <> 0 then
      Result[i + 1] := '1'
    else
      Result[i + 1] := '0';
  end;
end;

function Bin32ToInt(const s: string): LongWord;
var
  i: Integer;
begin
  Result := 0;
  for i := 1 to Length(s) do
  begin
    Result := Result shl 1;
    if s[i] = '1' then
      Inc(Result);
  end;
end;

function ReverseBits(n: LongWord): LongWord;
var
  bin, rev: string;
  i: Integer;
begin
  bin := IntToBin32(n);
  SetLength(rev, Length(bin));
  for i := 1 to Length(bin) do
    rev[i] := bin[Length(bin) - i + 1];
  Result := Bin32ToInt(rev);
end;

function Bits(n: LongWord): string;
var
  bin: string;
  i: Integer;
begin
  bin := IntToBin32(n);
  Result := '';
  for i := 0 to 3 do
  begin
    if i > 0 then
      Result := Result + ' ';
    Result := Result + Copy(bin, i * 8 + 1, 8);
  end;
end;

var
  a, b: LongWord;
  ra, rb: LongWord;

begin
  a := 19;
  b := 3;

  ra := ReverseBits(a);
  rb := ReverseBits(b);

  Writeln('Original 19: ', Bits(a));
  Writeln('Reversed 19: ', Bits(ra));
  Writeln;
  Writeln('Original 3:  ', Bits(b));
  Writeln('Reversed 3:  ', Bits(rb));
end.



{
run:

Original 19: 00000000 00000000 00000000 00010011
Reversed 19: 11001000 00000000 00000000 00000000

Original 3:  00000000 00000000 00000000 00000011
Reversed 3:  11000000 00000000 00000000 00000000

}

 



answered Apr 4 by avibootz
...