Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Bitwise Operators: Combining Efficiency and Ease of Use-2 : Page 2


advertisement
Operators' Functionality
Unlike the logical and relational operators !, &&, ||, >, ==, etc., which yield a Boolean value, bitwise operators yield a sequence of bits in the form of an integral datatype such as char, short, int, and so on. The bitwise operators and their names are:
  • ~ bitwise NOT, or one's complement (unary)
  • & bitwise AND
  • | bitwise OR
  • ^ bitwise XOR (exclusive OR)
Here's a brief description of each operator and its functionality. The ~ operator flips, or reverses, every bit in a sequence:

typedef unsigned char BYTE; BYTE s=127; //binary: 0111 1111 BYTE flipped_s= ~s; //dec 128, binary 1000 0000

Author's Note: Bit and byte ordering are platform-dependent. Certain processors read bits from right-to-left. On such machines, the rightmost bit is also the least significant bit (LSB). On other processors the LSB is the leftmost bit. All the examples given here use an order that is similar to the way humans read numbers such as 345, whereby the least significant digit is the rightmost one. To improve readability, I inserted a blank between every four bits and have confined my examples to unsigned char. In real code, you may of course use any integral type.

The operator & ands every bit in a sequence with a corresponding bit of another sequence. For example, applying & to the following bit strings



0011 1111 //decimal value: 63 0100 0011 //decimal value 67: produces 0000 0011: BYTE s1 = 63; // hex 0x3f, binary 0011 1111 BYTE s2 = 67; // 0x43, 0100 0011 BYTE res = s1 & s2; // 0x03, 0000 0011

The | operator ors every bit in a sequence with a corresponding bit of another sequence. For example:

BYTE s1 = 63; // 0x3f, 0011 1111 BYTE s2 = 67; // 0x43, 0100 0011 BYTE res = s1 | s2; // 0x7f, 0111 1111

The ^ operator xors every bit in a sequence with a corresponding bit of another sequence. For every such pair, the result is 1 only if one of the two bits equals 1. Otherwise, the result is 0:

BYTE s1=63; // 0x3f, 0011 1111 BYTE s2=67; // 0x43, 0100 0011 BYTE res= s1 ^ s2; // 0x7c, 0111 1100



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date