AndreiL
Welcome to AndreiL.
Enjoy your time.
Please log in.

Bitwise numbers - odd or even C++

Go down

Bitwise numbers - odd or even C++

Post by Lucaci Andrei on Thu Jun 14, 2012 11:30 pm

Ok. In this tutorial I will explain a simple thing: how to see if a number is odd or even using the bitwise AND.
Let's start with AND's truth table:

1
2
3
4
5
This is the table
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 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
9
10
11
Decimal     Bianry
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 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:

1
2
3
4
5
6
7
8
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:

1
2
3
4
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
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* parity.cpp
* parity.cpp is licensed under GNU GENERAL PUBLIC LICENSE
* Created on: Jun 15, 2012
* Author: sin
*/

#include <iostream>
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: "<<i<<" is even.\n";
else cout<<"i: "<<i<<" is odd.\n";
}
return (0);
}


avatar
Lucaci Andrei
"Tata Lor"


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

View user profile http://www.andreil.wgz.ro

Back to top Go down

Back to top


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