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.

Bitwise operators

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

//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.

Tags:,

Leave a Reply