[原創]Matlab 之按位操作


在硬件語言 Verilog 中按位操作是相對容易的,在C語言中一樣的用好邏輯符號 “|”、“!”、“&”、“>>” 等即可。但是在 Matlab 中一些類似的操作是判斷或者邏輯用法,不能用在按位操作上。那么在其中就需要用到函數來進行操作了。

在此記錄兩種按位操作的方法:按位左右移 bitshift,按位與 bitand

按位左右移 bitshift

C = bitshift(A,K) returns the value of A shifted to the left by K bits, 
    where A is a signed or unsigned integer array. Shifting by K bits
    is the same as multiplication by 2^K. Negative values of K are allowed 
    and this corresponds to shifting to the right, or dividing by 2^ABS(K) 
    and rounding to the nearest integer towards negative infinity. If the 
    shift causes C to overflow the number of bits in the integer class of A, 
    then the overflowing bits are dropped.
 
    If A is a double array, then all elements must be non-negative integers
    less than or equal to intmax('uint64'), and bitshift 
    drops any bits overflowing 64 bits.

其中K為正表示向左移,K 為負值表示向右移;示例如下有:

>> bitshift(5,1)

ans =

    10

>> bitshift(5,-1)

ans =

     2

按位與 bitand

C = bitand(A,B) returns the bitwise AND of arguments A and B, 
    where A and B are signed or unsigned integer arrays. If A and B are
    double arrays, then they must contain non-negative integer elements
    less than or equal to intmax('uint64').

兩個簡單的示例如下:

>> bitand(5,4)

ans =

     4

>> bitand(5,15)

ans =

     5

其他還有一些按位操作的函數,可以參考如下。

See also 
*bitor*, *bitxor*, *bitcmp*, *bitshift*, *bitset*, *bitget*, *intmax*.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM