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 right 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 right
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 right
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: [email protected] [mailto:[email protected]]
On Behalf Of Marshland Engineering
Sent: Monday, 21 June 2010 10:05 p.m.
To: [email protected]
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
_______________________________________________
NZ Borland Developers Group - Delphi mailing list
Post: [email protected]
Admin: http://delphi.org.nz/mailman/listinfo/delphi
Unsubscribe: send an email to [email protected] with Subject:
unsubscribe