[C] numerical operation

最近閒著,來複習一下數值運算...

Binary representation:
1 byte = 8 bits
可以表示 0~255 或 -128~127, 至於程式表示負數的方式, 是由硬體決定。
一般表示方式為:
a.用最高位的那個bit(the most significant bit, MSB)表示正負數
b.當MSB=0, 表示0~127, 當MSB=1, 則以2's complement看之.
ex. 00000011=3
10000001=01111111=-127 (作法: 從LSB開始, 第一個為1的bit不動,其餘的0->1, 1->0)
10000000=10000000=-128
11111111=00000001= -1

Binary Logical Operator:
'~':
。補數運算子
。ex. ~(1001101) -> 0110010
'&':
。ex. 10010011 & 00111101->00010001
'|':
。ex. 10010011 | 00111101->10111111
'^':
。位元間作運算,只有當1&0或0&1時結果才為1.
。ex. 10010011 ^ 00111101->10101110


ㄧ個常用的integer2Binary涵式:

char* Int2Bin(int n, char *pb){
    int len = 8*sizeof(int);
    int i;
    for(i=1;i<=len;i++, n>>=1)
    {
          pb[len-i]=(1&n)|'0'
     }
     pb[len+1]='\0';
}

Comments

Popular posts from this blog

股票評價(Stock Valuation) - 股利折現模型

openwrt feed的使用

How to convert Markdown into HTML