DelphiDabbler Code Snippets Database

Snippet Selection

The following snippets from the Code Snippets Database have been requested.

IntToBinary (Integer overload)

Returns a string containing the binary value of 32 bit signed integer Value. Digits indicates the minimum number of binary digits to return.

function IntToBinary(Value: Integer; const Digits: Byte): string; overload;
const
  // Binary digit characters
  BinaryDigits: array[0..1] of Char = '01';
begin
  Result := '';
  while Value <> 0 do
  begin
    Result := BinaryDigits[Value and 1] + Result;
    Value := Value shr 1;
  end;
  Result := PadRight(Result, '0', Digits);
end;

IntToBinary (Int64 overload)

Returns a string containing the binary value of 64 bit signed integer Value. Digits indicates the minimum number of binary digits to return.

function IntToBinary(Value: Int64; const Digits: Byte): string; overload;
const
  BitsPerInt32 = 8 * SizeOf(Integer);
var
  HiDigits: Byte;
begin
  if SysUtils.Int64Rec(Value).Hi = 0 then
    Result := IntToBinary(Integer(SysUtils.Int64Rec(Value).Lo), Digits)
  else
  begin
    if Digits > BitsPerInt32 then
      HiDigits := Digits - BitsPerInt32
    else
      HiDigits := 0;
    Result := IntToBinary(Integer(SysUtils.Int64Rec(Value).Hi), HiDigits)
      + IntToBinary(Integer(SysUtils.Int64Rec(Value).Lo), BitsPerInt32);
  end;
end;

View the whole database.

Go to the DelphiDabbler website.