Re: Convert number to binary notation

Posted by Bill DelphiMan on November 20, 2007

In Reply to Re: Convert number to binary posted by Geof on November 14, 2007

: Delphi has the built-in functions IntToStr (returns a string that is the decimal representation of a number) and IntToHex (returns a string that is the hexadecimal representation of a number). But alas, Delphi has no "IntToBinary" function.
: You'll have to write the function yourself ;)
: Or otherwise, search the Net for a library that contains such a function. If you find it, maybe let me know how it goes? :-p

If you want to convert the ASCII code of a character C to a string S, first get the decimal value of the ASCII code with Ord(C). Next, convert this to a string S that contains the binary representation:

S := IntToBin8(Ord(C));

Here's a Delphi source code example for the integer-to-binary function IntToBin8, that returns a string of 8 characters representing the binary form of an integer (such as '01000001' for 65):

function IntToBin8(I: integer): string;
begin
  Result := '';
  while I > 0 do begin
    Result := Chr(Ord('0') + (I and 1)) + Result;
    I := I shr 1;
  end;
  while Length(Result) < 8 do
    Result := '0' + Result;
end;

Thus, after S := IntToBin8(Ord('A'))
S contains '01000001'.

Related articles

       

Follow Ups