Thứ Hai, 19 tháng 11, 2012

Các phép toán trên bit


Các phép toán trên bit:
Các phép toán trên bit được thực hiện trên hệ nhị phân, nhanh.
1.      Phép not:
not bit 0 à bit 1.
not bit 1 à bit 0.
Ví dụ: not 0111 (7) = 1000 (8).
2.      Phép and:
0 and 0 = 0
0 and 1 = 0
1 and 0 = 0
1 and 1 = 1
Ví dụ: 0101 (5) and 0011 (3) = 0001 (1)
3.      Phép or:
0 or 0 = 0
0 or 1 = 1
1 or 0 = 1
1 or 1 = 1
Ví dụ: 0101 (5) or 0011 (3) = 0111 (7)
4.      Phép xor:
0 xor 0 = 1
1 xor 1 = 1
1 xor 0 = 0
0 xor 1 = 0
5.      Dịch bit:
0001110 (14) à left shift: 0011100 (28); right shift: 0000111 (7)
6.      Các phép toán bit trên các ngôn ngữ pascal, C/C++:
C/C++:
·        not: ~
·        and: &
·         or: |
·        xor: ^
·        left shift: <<
·        right shift: >>
Pascal:
·        not: not
·        and: and
·        or: or
·        xor: xor
·        left shift: shl
·        right shift: shr
Áp dụng:
1.      Xác định một số xem có phải là lũy thừa của hai không?
Không dùng thao tác trên bit (bit manipulation):
C/C++:
bool IsPowerTwo(int x)
{
      bool res;
      if(x > 0)
      {
                  while((x % 2) == 0)
                  {
                              x /= 2;
                  }
                  res = (x == 1);
      }
      else res = false;
     
      return res;
}

freepascal:

function IsPowerTwo(x:longint):boolean;
begin
    if(x > 0) then
        begin
            while(x mod 2 = 0) do x := x div 2;
            IsPowerTwo := (x = 1);
        end
    else IsPowerTwo := false;
end;

Sử dụng thao tac trên bit (bit manipulation):

C/C++:

bool IsPowerTwo(int x)
{
      return x && !(x & (x - 1));  
}

freepascal:

function IsPowerTwo(x:longint):boolean;
begin
    IsPowerTwo := (x > 0) and not((x and (x - 1)) <> 0);
end;

2.       Bật bit thứ i:
C/C++:
int SetBit(int x, int i)
{
      return x | (1 << i);     
}

freepascal:

function SetBit(x:longint;i:longint):longint;
begin
    SetBit := x or (1 shl i);
end;

3.      Xóa bit thứ i:
C/C++:
int ClearBit(int x, int i)
{
      return x&(~(1<<i));
}
freepascal:
function ClearBit(x:longint;i:longint):longint;
begin
    ClearBit := x and (not (1 shl i));
end;

4.      Test bit:
C/C++:
bool TestBit(int x, int i)
{
      return x & (1 << i);
}

freepascal:

function TestBit(x:longint; i:longint):boolean;
begin
    TestBit := (x and (1 shl i)) <> 0;
end;



Tài liệu tham khảo:

Không có nhận xét nào:

Đăng nhận xét