How do you find the position of the most significant bit (MSB) of an unsigned integer in Pascal

1 Answer

0 votes
program FindMostSignificantBit;

{$mode objfpc}{$H+}

uses
  SysUtils;

{
  Returns the zero-based position of the most significant set bit (MSB)
  in an unsigned 64-bit integer.

  Examples:
    Value = 1   -> 0
    Value = 2   -> 1
    Value = 8   -> 3
    Value = 15  -> 3

  Parameters:
    Value - Unsigned integer to inspect.

  Returns:
    -1 if Value is 0 (no bits are set).
    Otherwise, the zero-based index of the highest set bit.
}
function MsbPosition(const Value: QWord): Integer;
var
  CurrentValue: QWord;
  Position: Integer;
begin
  if Value = 0 then
    Exit(-1);

  CurrentValue := Value;
  Position := 0;

  while CurrentValue > 1 do
  begin
    CurrentValue := CurrentValue shr 1;
    Inc(Position);
  end;

  Result := Position;
end;

var
  Value: QWord;
  Position: Integer;
begin
  { Example value. In a real application, this may come from user input. }
  Value := 4660;  { $1234 }

  Position := MsbPosition(Value);

  if Position >= 0 then
    WriteLn('MSB position of ', Value, ' is ', Position)
  else
    WriteLn('Value contains no set bits.');

  { Additional test cases }
  WriteLn('MSB(1)  = ', MsbPosition(1));
  WriteLn('MSB(8)  = ', MsbPosition(8));
  WriteLn('MSB(15) = ', MsbPosition(15));
  WriteLn('MSB(0)  = ', MsbPosition(0));
end.


{
run:

MSB position of 4660 is 12
MSB(1)  = 0
MSB(8)  = 3
MSB(15) = 3
MSB(0)  = -1

}

 



answered Sep 30 by avibootz
...