位置:首頁 > 高級語言 > Matlab教學 > MATLAB位運算

MATLAB位運算

MATLAB提供位運算,如'位','位或'和'位不操作,移位操作等各種函數

以下的表格顯示了常用的按位運算:

函數 目的/作用
bitand(a, b) Bit-wise AND of integers a and b
bitcmp(a) Bit-wise complement of a
bitget(a,pos) Get bit at specified position pos, in the integer array a
bitor(a, b) Bit-wise OR of integers a and b
bitset(a, pos) Set bit at specific location pos of a
bitshift(a, k) Returns a shifted to the left by k bits, equivalent to multiplying by 2k. Negative values of k correspond to shifting bits right or dividing by 2|k| and rounding to the nearest integer towards negative infinite. Any overflow bits are truncated.
bitxor(a, b) Bit-wise XOR of integers a and b
swapbytes Swap byte ordering

例子

創建一個腳本文件,並鍵入下麵的代碼:

a = 60; % 60 = 0011 1100   
b = 13; % 13 = 0000 1101 
c = bitand(a, b)      % 12 = 0000 1100  
c = bitor(a, b)       % 61 = 0011 1101 
c = bitxor(a, b)      % 49 = 0011 0001 
c = bitshift(a, 2)    % 240 = 1111 0000 */
c = bitshift(a,-2)    % 15 = 0000 1111 */

當運行該文件,它會顯示以下結果:

c =
    12
c =
    61
c =
    49
c =
   240
c =
    15