home *** CD-ROM | disk | FTP | other *** search
/ Delphi Programming Unleashed / Delphi_Programming_Unleashed_SAMS_Publishing_1995.iso / units / binary.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1995-03-21  |  1.6 KB  |  66 lines

  1. {$D-}
  2. unit Binary;
  3.  
  4. interface
  5.  
  6. function ShowBits(B : Byte): string;
  7. procedure SetBit(Position: Integer; Value : Byte; var ChangeByte : Byte);
  8. function BitOn(Position: Integer; TestByte: Byte) : Boolean;
  9.  
  10. implementation
  11.  
  12. { This function accepts a byte parameter and returns
  13.   a string of eight ones and zeros indicating the
  14.   binary form of a bite. }
  15. function ShowBits(B : Byte): string;
  16. var
  17.   i: Integer;
  18.   bt: Byte;
  19.   s: string;
  20. begin
  21.   bt := $01;
  22.   s := '';
  23.   for i := 1 to 8 do begin
  24.     if (b And bt) > 0 then
  25.        S := '1' + s
  26.     else
  27.       s := '0' + s;
  28.      {$R-}
  29.       bt := bt shl 1;
  30.      {$R+}
  31.     end;
  32.   ShowBits := s;
  33. end;
  34.  
  35. { This procedure sets a particular bit in the byte changebyte
  36.   to either 1 or 0. The bit is specified by Position, which can range
  37.   from 0 to 7. In Value, put 1 if you want the bit Position set to 1
  38.   and put 0 if you want bit Position set to 0. The right byte is Position
  39.   0, the far left is Position 7. Based on a routine found in
  40.   Turbo Pascal by Stephen K O'Brian. }
  41. procedure SetBit(Position : Integer; Value : Byte; var ChangeByte : Byte);
  42. var
  43.   Bt : Byte;
  44. begin
  45.   bt := $01;
  46.   bt := bt shl Position;
  47.   if Value = 1 then
  48.     ChangeByte := ChangeByte or bt
  49.   else begin
  50.     bt := bt xor $FF;
  51.     ChangeByte := ChangeByte and bt;
  52.   end;
  53. end;
  54.  
  55. { This function tests if a bit in TestByte is turned on (equal to 1).
  56.   If the bit indicated by Position is turned on, then BitOn returns True. }
  57. function BitOn(Position : Integer; TestByte : Byte) : Boolean;
  58. var
  59.   bt : Byte;
  60. begin
  61.   bt := $01;
  62.   bt := bt shl Position;
  63.   BitOn := (bt and TestByte) > 0;
  64. end;
  65.  
  66. end.