[DUG] IntToBin

Jianming Lin (FMI) jianmingl at fmi.co.nz
Tue Jun 22 09:27:04 NZST 2010


Hi,

 

For example :

IntToBin(5, 3)

 

digit is 3 at begining.

result := StringOfChar('0', 3); // each digit is set to '0' so default
result is: '000';

value(5) and 1; // 5 in binary is 0101, (0101 and 0001) means take the
first bit from left result is 1;

 

result[digit] := '1'; // set the first binary digit char as '1';

 

dec(digit);     //digit decrease to 2;

 

value := value shr 1;  // value of 1101 shift right by 1 result is :
0010

 

 

next loop:

==============

value(0010) and 1; // (0010 and 0001), take the first bit from left
result is 0;

                   // so take no action, left the rsult[2] as it is --
'0'

 

dec(digit);     //digit decrease to 1;

 

value := value shr 1;  // value of 0010 shift right by 1 result is :
0001

 

 

next loop:

==============

value(0001) and 1; // (0001 and 0001), take the first bit from left
result is 1;

result[1] := '1';  // set the third (from right) binary digit char as
'1';

 

dec(digit);     //digit decrease to 0;

 

value := value shr 1;  // value of 0001 shift right by 1 result is :
0000

 

 

________________________________

From: delphi-bounces at delphi.org.nz [mailto:delphi-bounces at delphi.org.nz]
On Behalf Of Marshland Engineering
Sent: Monday, 21 June 2010 10:05 p.m.
To: delphi at delphi.org.nz
Subject: [DUG] IntToBin

 

Hi Chaps 

 

I found this on the web and it works but I don't understand how ? 

 

Can anyone explain it ?

 

function IntToBin ( value:Integer; digits: integer ): string;
begin
    result := StringOfChar ( '0', digits ) ;
    while value > 0 do begin
      if ( value and 1 ) = 1 then
        result [ digits ] := '1';
      dec ( digits ) ;
      value := value shr 1;
    end;
end;

 

Thanks Wallace

 

 

 

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://listserver.123.net.nz/pipermail/delphi/attachments/20100622/d30d2741/attachment.html 


More information about the Delphi mailing list