An Entertaining Example For The Usage of Bitwise Operations in Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

An Entertaining Example for the Usage of

Bitwise Operations in Programming


Hristina Kostadinova, Krasimir Yordzhev
South-West University "Neofit Rilski"
Blagoevgrad, Bulgaria
[email protected] [email protected]
Abstract: The present study is meant to fill in some information gaps
occurring in the most widespread and well-known educational and reference
literature about programming. The stress is laid on a very useful instrument
- the bitwise operations, topic which is, unfortunately, seldom dealt with in
most of the well-known books on programming. In addition, the research is
very useful as regards the topic of overloading operators in any Object-
oriented programming course. Given some appropriate examples, with the
emphasis being laid on some particular and data structures language con-
structions, the results are quite interesting. The algorithm of solving the
popular Sudoku puzzle is one such entertaining example.
Keywords: Object-oriented programming, bitwise operation, class, set,
overloading operators, Sudoku matrix, Sudoku puzzle
1. INTRODUCTION
The use of bitwise operations is a popular and well-working method,
used in C/C++ and Java programming languages. Unfortunately, in many
widespread books on this topic there is only scarce or incomplete informa-
tion as to how exactly bitwise operators function [4,14,15,16,20]. The aim of
this article is to bridge this information gap to a certain extent and present a
meaningful example of a programming task, where the use of bitwise opera-
tors is appropriate, in so far as to facilitate the work and increase the effi-
ciency of the respective algorithm. Thus, we shall help the programming
teachers in their work by presenting a good programming example, which
demonstrates the use of bitwise operations in C/C++.
Some applications of the bitwise operations in the realization of algo-
rithms designed to determine quantitative evaluations in the textile industry,
as shown in [7,11,12].
Let ,
{
0 1 1
, , ,
m
M m m m
-
= K } M m = be a finite and discrete set. By the
rule of thumb [17], each subset could be denoted by means of a Boolean
vector
( )
0 1 1
, , ,
m
b A b b b
-
= K , where A b
i i
e = 1 and A b
i i
e = 0 ,


1 ,..., 2 , 1 = m i . A great memory economy could be achieved, if natural
numbers are presented in a binary number system, where the number
zero corresponds to null set, while the number , which in a binary
number system is written by means of ones, corresponds to the basic
set
2
m
- 1
m
M . Thus, a natural one to one correspondence between the integers of
the closed interval | | 1 2 , 0
m
and the set of all subsets of M is achieved.
The integer | | 1 2 ,
m
0 e
i
A
a
1 ,..., 2 , 1 = m i
i
corresponds to the set , if for every
the -bit of the binary representation of equals one, and if
and only if
M A_
a
e . The need of the use of bitwise operations naturally
arises in cases involving the computer realization of various operations with
different sets of numbers.
Such an approach is also comfortable and quite efficient, given a rela-
tively small cardinal number m M = of the basic set M , and it also has a
significant importance, in relation to the operating system and programming
environment that is used. This is so, because m bits are necessary to en-
code in the abovementioned method a set, which a subset of M , where
M m = . And if k-bits are given for the type integer in the programming en-
vironment dealing with data, then 1 +
(

k
m
variables of that certain kind will
be necessary, so as to put the abovementioned ideas into practice, where
[ ] x denotes the function the whole part of x . Four bytes (thirty-two bits)
are necessary to write a program that can solve a Sudoku puzzle in the size
of if we use the set theory method at
2
n
2
n 5 s n . In this case, every set
of the kind { }
s
A o o o ,..., ,
2 1
= , where 1 ,
2
n
i
s so s i 2 , 1 ,..., = , , or
the null set, could be simply encoded with an integer.
2
n 0 s s s
The programming realization of the problem of finding prime numbers
using the method Sieve of Eratosthenes [1,5,8,19] has become a classical
example for the use of sets in programming. Here we have to emphasize
that a mistake has been made in [19], concerning this methods realization,
and namely the number 1 has been reckoned among the set of the prime
numbers. Such a mistake is inadmissible if the method is applied at schools,
as the users may be confused.
How to construct a faster algorithm, solving the problem for receiving
all binary matrices, which contain exactly ones in each row and
each column, with the help of the set theory and the operations over sets, is
shown in [13].
n n k
Unfortunately the programming languages C/C++ and Java do not
support a standard type set, whereas the Pascal language does [1,5,8,19].


For this reason, if there should be a need to use the language of sets in the
realization of some of our algorithms, and if there should be a need to write
a program in some of these languages, we have to look for additional in-
struments to work with sets, such as, for example, the associative contain-
ers set and multiset, realized in Standard Template Library (STL) [15]. The
template class set of the system of computer algebra Symbolic C++ can
also be used. The programming code is given in details in [9]. Of course,
another class set can also be built, and specific methods of this class can
be described, as a means of training. This is a good exercise, having in
mind the fact that the cardinal number of the basic (universal) set is not
very big. For example the standard Sudoku puzzle has basic set the set of
the integers from 1 to 9 plus the empty set.
We shall examine the entertaining problem with Sudoku solving algo-
rithms, which is very interesting to many students. Sudoku is popular puzzle
nowadays, populating the recreation pages of many newspapers and mag-
azines, and it could also be found on many websites. Sudoku, or Su Doku,
is a Japanese word (or phrase) meaning something like Number Place.
On the other hand, Sudoku matrices find an interesting combinatorial
application. The connection between the set of all m m permutation matri-
ces (i.e. binary matrices which contain just one 1 in every row and every
column) and the set of all m m Sudoku matrices, is shown in [2].
2. TASK LAYOUT AND DESCRIPTION OF THE ALGORITHM
USING THEORETIC SET OPERATIONS
Let n be random positive integer and let
2
n m= . Let ( )
j i
s S = be a
square m m matrix (square table), all elements in this table are inte-
gers, belonging to the closed interval ] , 1 [ m . The matrix S is divided
to
2
n , n n square submatrices, which are not intersected and will
be called blocks, with the help of 1 n horizontal and 1 n vertical
lines (the matrix S , when 3 = n , is shown on fig.1).



S
11
S
12
S
13
S
14
S
15
S
16
S
17
S
18
S
19
S
21
S
22
S
23
S
24
S
25
S
26
S
27
S
28
S
29
S
31
S
32
S
33
S
34
S
35
S
36
S
37
S
38
S
39
S
41
S
42
S
43
S
44
S
45
S
46
S
47
S
48
S
49
S
51
S
52
S
53
S
54
S
55
S
56
S
57
S
58
S
59
S
61
S
62
S
63
S
64
S
65
S
66
S
67
S
68
S
69
S
71
S
72
S
73
S
74
S
75
S
76
S
77
S
78
S
79
S
81
S
82
S
83
S
84
S
85
S
86
S
87
S
88
S
89
S
91
S
82
S
93
S
94
S
95
S
96
S
97
S
98
S
99

Fig. 1:

Let denote by ,
l k
A n l k s s , 1 the blocks in the above described matrix
( )
j i
s S = . Then by definition if
l k
A
j i
s e , then
kn i n k s < ) 1 (
and
) 1 ( ) 1 ( s < l j l .
Let belong to the block and let i and
j i
s
l k
A j be known. Then it is
easy to guess that and l can be calculated with the help of the formulas k
1
1
+
(


=
n
i
k
and
1
1
+
(


=
n
j
l ,
where, as usual, we denote by | | x the function: whole part of the real
number x .
We say that ( )
j i
s S = , is a Sudoku matrix if there is
just one number of the set
2
, 1 n m j i = s s
{ }
2
Z , , 2 , 1 n m
m
= = in every row, every column
and every block.
The Sudoku puzzle is quite popular these days. The user is given a
Sudoku matrix, in which some of the elements have been erased. The miss-
ing elements could be equal to 0. The users task is to restore the missing
elements of the Sudoku matrix. It is supposed that the authors of the par-
ticular puzzle have chosen the missing elements in such a way that the
problem has only one solution. This condition will be ignored. In this study
we will build our programming product so that it can show the number of
every possible solution. If the task has no solution this number will be zero.
The most popular Sudoku puzzles are with 3 = n , i.e. 9 = m .


We are going to describe an algorithm for creating a computer pro-
gram, which can find all solutions (if there are any) of random Sudoku puz-
zle. For this purpose, we will use the knowledge of the set theory.
We examine the sets , and , where ,
. For every
i
R
m ,
j
C
l k
B
2
, 1 n m j i = s s
n l k s s , 1 i , 2 , 1 = , the set consists of all missing num-
bers in the -th row of the matrix. Analogously we define the sets ,
correspondingly for the missing numbers in the
j
R
i
j
C
m j , , 2 , 1 = j -th column
and ,
l k
B n , l , k , 2 , 1 = correspondingly for the missing numbers in the
blocks of .
l k
A S
Whenever the algorithm comes into operation it traverses many times
all of the elements , such that S s
j i
e 0 =
j i
s , i.e. these are the elements,
which real values we have to find.
Let 0 =
j i
s and let
l k j i
A s e . We assume
l k j i
B C R P = .
Then the following three cases are possible:
i) | = P (empty set). The task has no solution in this case;
ii) { } d P = , { } m Z d
m
, , 2 , 1 = e , i.e. P : the number of the elements of
P is equal to 1 ( P is a set containing one element). Then the only one
possibility for
j i
s is d s
j i
= , i.e. we have found the unknown value of
j i
s in
this case. After this we remove the common element d from the sets
i
R ,
j
C and
l k
B , and then we continue to the next zero element of the matrix S
(if there is such an element);
iii) 2 > P . Then, we cannot say anything about the unknown value of
j i
s and we move on the next missing (zero) element of the matrix S .
We traverse all zero elements of the matrix , until one the following
events occur:
S
1) For some } , , 2 , 1 { , m j i e is true , but 0 =
j i
s
| = =
l k j i
B C R P ;
2) All elements in become positive; S


3) All zero elements of are traversed, but neither event 1, nor
event 2 occur. In other words, for all the remaining zero elements in , the
above described case iii is always true.
S
S
In case any of the events 1 or 2 occurs, then the procedure is
brought to a halt and the result visualizes on the screen.
In case event e3 occurs, then the algorithm has to continue operating
by using other methods such as, for example, applying the trial and error
method. In this particular case, the method would consist of the following
steps:
We choose random S s
j i
e , such that 0 =
j i
s and let 1
1
+
(


=
n
i
k ,
1
1
+
(


=
n
j
l . Let } {d B P , , ,
2
d d
1 t l k j i
C R = = . Then for every
, we assume . Such an assumption is called a
random trial. We count the number of all random trials, until the solution is
found in the programming realization of the algorithm. Then, we solve the
problem for finding the unknown elements of the Sudoku matrix, which con-
tain one element less than the previous matrix. It is convenient to use a re-
cursion here. The procedure is halted if event e1 or e2 occurs. It is abso-
lutely certain to occur (i.e. there will not be an infinite cycle), because
whenever we perform random trials, we reduce the number of the zero ele-
ments by 1.
P d
r
e t r , , 2 , 1 =
r j i
d s =
3. BITWISE OPERATORS IN C/C++
Bitwise operations can be applied for integer data type only, i.e. they
cannot be used for float and double types. For the definition of the bitwise
operators in C/C++ and some of their elementary applications could be
seen, for example in [3,6,10,18].
We assume as usual that bits numbering in variables starts from right
to left, and that the number of the very right one is 0.
Let y x, and z are integer variables of one type, for which bits are
needed. Let
w
x and are initialized and let the y y x z o = assignment is
made, where o is one of the operators & (bitwise AND), | (bitwise inclusive
OR) or ^ (bitwise exclusive OR). For each 1 , , 1 , 0 = w i the new contents
of the i bit in z will be as it is presented in the following table:




The i bit of
x
The i bit of
y
The i bit of
y x &
The i bit of
y x |
The bit of

i
x^y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

In case x z ~ = , if the bit of i x is 0, then the i bit of z becomes 1,
and if the i bit of x is 1, then the i bit of z becomes 0, 1 , 0 , 1 , = w i
In case is a nonnegative integer, then the statement
(bitwise shift left) will write in the
k ; k x z << =
) ( k i +

bit of z the value of the bit of k x ,
where 1 , 1 , 0 , = k w i , and the very right bits of k z will be filled by ze-
roes. This operation is equivalent to a multiplication of x by . The state-
ment functions similarly (bitwise shift right). But we must be
careful here, as in various programming environments this operator has dif-
ferent interpretations somewhere bits of
k
2
k x z >> =
k z from the very right place are
compulsory filled by 0 (logical displacement), and elsewhere the very right
bits of k z are filled with the value from the very left (sign) bit; i.e. if the
number is negative, then the filling will be with 1 (arithmetic displacement).
Therefore it is recommended that we use unsigned type of variables (if the
opposite is not necessary) whenever we work with bitwise operations.
The effectiveness of the function computing is the direct result of
the definition of the operator bitwise shift left, where is a nonnegative in-
teger:
k
2
k

unsigned int Power2(unsigned int k) {
return 1<<k;
}
To compute the value of the i bit of an integer variable x we can use
the function:

int BitValue(int x, unsigned int i) {
if ( (x & (1<<i) ) == 0 ) return 0;
else return 1;
}
Bitwise operators are left associative.
The priority of operators in descending order is as follows: bitwise
complement ~; arithmetic operators * (multiply), / (divide), % (remainder or
modulus); arithmetic operators + (binary plus or add) - (binary minus or sub-


tract); the bitwise operators << and >>; relational operators <, >, <=, >=, ==,
!=; bitwise operators &,^ and |; logical operators && and ||.
4. DESCRIPTION OF THE CLASS SET BY MEANS OF OVER-
LOADING OPERATORS AND USING BITWISE OPERATIONS
class Set_N {
int n;
public:
/*Constructor without parameter creates empty set*/
Set_N();
/*Constructor with parameter creates the set, corresponding to every
bit position of the parameter*/
Set_N(int k);
/*Returns the integer encoding of the set*/
int get_n() const;
/*Overloading operators *, +, -, ==, <=*/
Set_N operator * (Set_N const &);
Set_N operator + (Set_N const &);
Set_N operator + (int k);
Set_N operator - (Set_N const &);
Set_N operator - (int k);
bool operator == (Set_N const &);
bool operator <= (Set_N const &);
/*Checks if the first parameter belongs to the given set*/
bool in(int k);
/*Destructor*/
~Set_N();
};
The realization of the Set_N methods is described below:
Set_N::Set_N() {n = 0;}
Set_N::Set_N(int k) {n = k;}
int Set_N::get_n() const {
return n;
}
Set_N Set_N::operator * (Set_N const & s) {
return (this->n) & s.get_n();
}
Set_N Set_N::operator + (Set_N const & s) {
return (this->n) | s.get_n();
}
Set_N Set_N::operator + (int k) {
return (this->n) | (1<<(k-1));


}
Set_N Set_N::operator - (Set_N const & s) {
int temp = 0;
temp = this->n ^ s.get_n();
return (this->n) & temp;
}
Set_N Set_N::operator - (int k) {
return (this->n) ^ (1<<(k-1));
}
bool Set_N::operator == (Set_N const & s) {
return ((this->n ^ s.get_n()) == 0);
}
bool Set_N::operator <= (Set_N const & s) {
return ((this->n & s.get_n()) == n);
}
bool Set_N::in(int k, Set_N const & s) {
return this->n & (1<<(k-1));
}
5. REFERENCES

[1] Dahl, D. J., Dijkstra, E. W., Hoare, C. A. R. (1972) Structured
Programming. Academic Press Inc.
[2] Dahl, G. (2009) Permutation matrices related to Sudoku.
Linear Algebra and its Applications 430, 24572463.
[3] Davis, S. R. (2000) C++ for dummies. IDG Books Worldwide.
[4] Horstmann, C. S. (1999) Computing concepts with C++ essen-
tials. John Wiley & Sons.
[5] Jensen, K., Wirth, N. (1985) Pascal User Manual and Report.
3
rd
ed., Springer-Verlag.
[6] Kernigan, B. W., Ritchie D. M. (1998) The C programming
Language. AT&T Bell Laboratories.
[7] Kostadinova, H., Yordzhev, K. (2010) A Representation of Bi-
nary Matrices. Mathematics and education in mathematics, v.
39, 198-206.
[8] Price, D. (1983) UCSD Pascal A Considerate Approach. Pren-
tice-Hall.
[9] Shi, T. K., Steeb, W.-H., Hardy, Y. (2000)Symbolic C++: An In-
troduction to Computer Algebra using Object-Oriented Pro-
gramming. Springer.



[10] Schildt, H. Java 2 A Beginners Guide. (2001) McGraw-Hill.
[11] Yordzhev, K. (2009) An example for the use of bitwise opera-
tions in programming. Mathematics and education in mathe-
matics, v. 38, 196-202
[12] Yordzhev, K., Kostadinova, H. (2010) Mathematcal Modeling
of the Weaving Structure Design Mathematics and education in
mathematics, v. 39, 212-220.
[13] Yordzhev, K., Stefanov, S. (2003) On Some Applications of
the Consept of Set in Computer Science Course. Mathematics
and Educations in Mathematics, v.32, 249-252.
[14] . (2005) ++
9-10 . , .
[15] . (2008) -
STL. , .
[16] , . (2006)
++. , .
[17] , ., . (2005) =++ -
, , , ISBN 954-8905-16-X.
[18] , . . (2004)
C++. , .
[19] , ., , . (1994) Pascal
99 . , Paraflow.
[20] . (2002) ++. , ,
, .

You might also like