Mega Code Archive

 
Categories / Delphi / Examples
 

Integer to binary string

Question: How can I convert an integer to a string of zeros and ones representing the binary values of the bits? Answer: The following example shows how to convert an integer to a "BinaryString" of zeros and ones by using the "shl" (shift bits left) macro to isolate the bits, and the "and" operator to test the bits. Example: function LongIntToBinString(BinValue : longint) : string; var i : integer; s : string; begin s := ''; for i := 31 downto 0 do if (BinValue and (1 shl i)) <> 0 then s := s + '1' else s := s + '0'; Result := s; end; procedure TForm1.Button1Click(Sender: TObject); begin Memo1.Lines.Add(LongIntToBinString($FF)); end;