AndreiL
Welcome to AndreiL.

# Bitwise numbers - odd or even C++

## Bitwise numbers - odd or even C++

Ok. In this tutorial I will explain a simple thing: how to see if a number is odd or even using the bitwise AND.

 `12345` `This is the table0 & 0 = 01 & 0 = 00 & 1 = 01 & 1 = 1`

Ok, so from what you see, the AND bitwise is true only when both digits are 1 and 0 otherwise. So, knowing that, let's take a look at some examples:

 ` 1 2 3 4 5 6 7 8 91011` `Decimal Bianry0 00001 00012 00103 00114 01005 01016 01107 01118 10009 1001`

This are the decimal and the binary equivalent numbers.
So, let's take for example number 0 and number 1, and let's make the 0&1 operation:

 `12345678` `0 0 0 0 &0 0 0 1-------0 0 0 0//You take from the table every single digit.//So first: it's from right to left: 0 with 1 from the table is 0, then 0 & 0 is zero. So the//answer is 0 0 0 0.`

Pretty neat, isn't it?

So, let's take for example 1&1:

 `1234` `0 0 0 1 &0 0 0 1-------0 0 0 1`

As you can see from the binary table, every even number ends with 0 and every odd number ends with 1. So, by bitwising AND with 1, the only thing that is taken into consideration is the right-most digit.
Without further adieu, here's the simple odd/even checker.

 ` 1 2 3 4 5 6 7 8 910111213141516171819202122` `/* * parity.cpp * parity.cpp is licensed under GNU GENERAL PUBLIC LICENSE * Created on: Jun 15, 2012 * Author: sin */#include using namespace std;bool isEven(int i){ if ((i&1)==0) return (true); return (false);}int main(){ for (int i=0;i<100;i++){ if (isEven(i)) cout<<"i: "<

_________________

Lucaci Andrei
"Tata Lor"

Number of messages : 222
Points : 2266743
Reputation : 1007
Registration date : 2008-08-15
Age : 26
Location : Cluj-Napoca

Permissions in this forum:
You cannot reply to topics in this forum