由D語言支持的位運算符列于下表中。假設(shè)變量A=60和變量B=13,則:
| 運算符 | 描述 | 示例 |
|---|---|---|
| & | 二進制AND拷貝操作,如果它存在于兩個操作數(shù)的結(jié)果。 | (A & B) will give 12 which is 0000 1100 |
| | | 二進制OR運算符拷貝位,如果它存在一個操作數(shù)中。 | (A | B) will give 61 which is 0011 1101 |
| ^ | 二進位異或運算符拷貝位,如果它被設(shè)置在一個操作數(shù),但不能同時使用。 | (A ^ B) will give 49 which is 0011 0001 |
| ~ | 二進制的補碼運算符是一元的,具有'翻轉(zhuǎn)'位的效果。 | (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. |
| << | 二進制左移位運算符。左操作數(shù)的值被移動由右操作數(shù)指定的位數(shù)。 | A << 2 will give 240 which is 1111 0000 |
| >> | 二進制右移運算。左操作數(shù)的值是正確的由右操作數(shù)指定的位數(shù)移動。 | A >> 2 will give 15 which is 0000 1111 |
試試下面的例子就明白了所有的D編程語言位運算符:
import std.stdio; int main(string[] args) { uint a = 60; /* 60 = 0011 1100 */ uint b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ writefln("Line 1 - Value of c is %d ", c ); c = a | b; /* 61 = 0011 1101 */ writefln("Line 2 - Value of c is %d ", c ); c = a ^ b; /* 49 = 0011 0001 */ writefln("Line 3 - Value of c is %d ", c ); c = ~a; /*-61 = 1100 0011 */ writefln("Line 4 - Value of c is %d ", c ); c = a << 2; /* 240 = 1111 0000 */ writefln("Line 5 - Value of c is %d ", c ); c = a >> 2; /* 15 = 0000 1111 */ writefln("Line 6 - Value of c is %d ", c ); return 0; }
當編譯并執(zhí)行上面的程序它會產(chǎn)生以下結(jié)果:
Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15