August 17, 2010
Bitwise operators in c++
Problem
Write a C++ function that takes a character as input and returns true if the second significant bit of the binary representation of the character is set (i.e equals to 1) otherwise return false.
Solution
This is a bitwise operations problem. First you need to shift the character one digit to the right then do an AND operation between the character and the constant (1)
c++ bitwise operators example
Here is a bitwise c++ example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
//Includes #include <iostream> //STD using namespace std; //Returns the least significant bit char* LSB (char c) { //Shift one digit to the right then AND with 1 if((c >> 1) & 1) { return "TRUE"; } else { return "FALSE"; } } //Main function void main() { //ASCII of (a) = 01100001 cout << "LSB(a) = " << LSB('a') << endl; //ASCII of (b) = 01100010 cout << "LSB(b) = " << LSB('b') << endl; //ASCII of (c) = 01100011 cout << "LSB(c) = " << LSB('c') << endl; //ASCII of (d) = 01100100 cout << "LSB(d) = " << LSB('d') << endl; } |
Please use the comments section below for questions or feedback. Thanks for visiting.