RSS

Watch ipl6 2013 live streaming

Watch ipl6 2013  live streaming...


http://www.hatpakha.com/sony-max-247

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Latest Mathematics suggestion for 2013 Madhyamik(10th)

Hurry!!!     Hurry!!!       Hurry!!!

Madhyamik exam or 10th exam (West Bengal Board, W.B.B.S.E) for year 2013 is not so far. Its coming.
Confusion with mathematics???
Don't worry . . .


Here is the suggestion for mathematics. Just download it. It will help you. (80-90% common.)
Lets download and solve the questions....


Link 1: Click here


[ Note: The suggestion is free. Please don't use it for sale. If you satisfy with this . please donate some money. call @ 08050264206. ]



Best of luck for your exam.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

TINY DEW SENSOR












                                                 

DEW (condensed moisture) adversely affects the normal performance of sensitive electronic devices. A low-cost circuit described here can be used to switch off any gadget automatically in case of excessive humidity. At the heart of the circuit is an inexpensive (resistor type) dew sensor element. Although dew sensor elements are widely used in video cassette players and recorders, these may not be easily available in local market. However, the same can be procured from authorised service centres of reputed companies. The author used the dew sensor for FUNAI VCP model No. V.I.P. 3000A (Part No: 6808-08-04, reference no. 336) in his prototype. In practice, it is observed that all dew sensors available for video application possess the same electrical characteristics irrespective of their physical shape/size, and hence are interchangeable and can be used in this project. The circuit is basically a switching type circuit made with the help of a popular dual op-amp IC LM358N which is configured here as a comparator. (Note that only one half of the IC is used here.) Under normal conditions, resistance of the dew sensor is low (1 kilo-ohm or so) and thus the voltage at its non-inverting terminal (pin 3) is low compared to that at its inverting input (pin 2) terminal. The corresponding output of the comparator (at pin 1) is accordingly low and thus nothing happens in the circuit. When humidity exceeds 80 per cent, the sensor resistance increases rapidly. As a result, the non-inverting pin becomes more positive than the inverting pin. This pushes up the output of IC1 to a high level. As a consequence, the LED inside the opto-coupler is energised. At the same time LED1 provides a visual indication. The opto-coupler can be suitably interfaced to any electronic device for switching purpose. Circuit comprising diode D2, resistors R5 and R6 and capacitor C1 forms a low-voltage, low-current power supply unit. This simple arrangement obviates the requirement for a bulky and expensive step-down transformer.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

8 Common Programming Mistakes

Learning to program can be tough--just ask anyone who's done it! Fortunately, a lot of problems happen over and over again--I've put together 8 of the most common problems that you'll run into as a new programmer.



1. Undeclared Variables:

 

int main()
{
  cin>>x;
  cout<
 
"Huh? Why do I get an error?" 
 
Your compiler doesn't know what x means. You need to declare it as a variable.
 
 int main()
{
  int x;
  cin>>x;
  cout<
 
 
 

2. Uninitialized variables:

 

int count;
while(count<100)
{
  cout<
 
 
"Why doesn't my program enter the while loop?"
 
In C++ variables are not initialized to zero. In the above snippet 
of code, count could be any value in the range of int. It might, 
for example, be 586, and in that situation the while loop's condition 
would never be true. Perhaps the output of the program would be 
to print the numbers from -1000 to 99. In that case, once again, 
the variable was assigned a memory location with garbage data 
that happened to evaluate to -1000. 
 Remember to initialize your variables.  
 
 

3. Setting a variable to an uninitialized value:

 

int a, b;
int sum=a+b;
cout<<"Enter two numbers to add: ";
cin>>a;
cin>>b;
cout<<"The sum is: "<
 
"What's wrong with my program?" 
 
Often beginning programmers believe that variables work like equations - if you assign a variable to equal the result of an operation 
on several other variables that whenever those variables change (a and b in this example), the value of the variable will change. 
In C++ assignment does not work this way: it's a one shot deal. 
Once you assign a value to a variable, it's that value until you
reassign the values. In the example program, because a and b are 
not initialized, sum will equal an unknown random number, no matter what the user inputs.  

 To fix this error, move the addition step after the input line.

int a, b;
int sum;
cout<<"Enter two numbers to add: ";
cin>>b;
cin>>a;
sum=a+b;
cout<<"The sum is: "<
 
 

4. Using a single equal sign to check equality:

 

char x='Y';
while(x='Y')
{
  //...
  cout<<"Continue? (Y/N)";
  cin>>x;
}
 
 
"Why doesn't my loop ever end?" 
 
If you use a single equal sign to check equality, your program 
will instead assign the value on the right side of the expression 
to the variable on the left hand side, and the result of this 
statement is TRUE. Therefore, the loop will never end. Use '== '
to check for equality; furthermore, to avoid accidental assignment, 
put variables on the left hand side of the expression and you'll 
get a compiler error if you accidentally use a single equal sign 
as you can't assign a value to something that isn't a variable.
 
 
 
char x='Y';
while('Y'==x)
{
  //...
  cout<<"Continue? (Y/N)";
  cin>>x;
}
 
 

5. Undeclared Functions:

 

int main()
{
  menu();
}
void menu()
{
  //...
}
 
"Why do I get an error about menu being unknown?" 
 
The compiler doesn't know what menu() stands for until you've 
told it, and if you wait until after using it to tell it that 
there's a function named menu, it will get confused. Always remember 
to put either a prototype for the function or the entire definition 
of the function above the first time you use the function. 
void menu();
int main()
{
  menu();
}
void menu()
{
  ...
}
 

6. Extra Semicolons:

 

int x;
for(x=0; x<100; x++);
  cout<
 
"Why does it output 100?" 
 
You put in an extra semicolon. Remember, semicolons don't go after 
if statements, loops, or function definitions. If you put one 
in any of those places, your program will function improperly.
 
int x;
for(x=0; x<100; x++)
  cout<
 
 
 

7. Overstepping array boundaries:

 

int array[10];
//...
for(int x=1; x<=10; x++)
  cout<
 
"Why doesn't it output the correct values?" 
 
 
Arrays begin indexing at 0; they end indexing at length-1. For 
example, if you have a ten element array, the first element is 
at position zero and the last element is at position 9. 
 
int array[10];
//...
for(int x=0; x<10; x++)
  cout<
 

8. Misusing the && and || operators:

 

int value;
do
{
  //...
  value=10;
}while(!(value==10) || !(value==20))
 
"Huh? Even though value is 10 the program loops. Why?" 
 
 
Consider the only time the while loop condition could be false: 
both value==10 and value==20 would have to be true so that the 
negation of each would be false in order to make the || operation
return false. In fact, the statement given above is a tautology; it is always true that value is not equal to 10 or not equal to 
20 as it can't be both values at once. Yet, if the intention is for the program only to loop if value has neither the value of 
ten nor the value of 20, it is necessary to use && : !(value==10) && !(value==20), which reads much more nicely: "if value is not 
equal to 10 and value is not equal to 20", which means if value is some number other than ten or twenty (and therein is the mistake 
the programmer makes - he reads that it is when it is "this" or "that", when he forgets that the "other than" applies to the entire 
statement "ten or twenty" and not to the two terms - "ten", "twenty" - individually). A quick bit of boolean algebra will help you 
immensely: !(A || B) is the equivalent of !A && !B (Try it and see). The sentence "value is other than [ten or twenty]" (brackets 
added to show grouping) is translatable to !(value==10 || value==20), and when you distribute the !, it becomes !(value==10) && !(value==20).
 
 
The proper way to rewrite the program:
 
 
int value;
do
{
  //...
  value=10;
}while(!(value==10) && !(value==20))
 
 
 

 

  

 

  

 

 

  

 

 

 

  

 

  

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Latest Mathematics suggestion for 2012 Madhyamik(10th)

Hurry!!!     Hurry!!!       Hurry!!!

Madhyamik exam or 10th exam (West Bengal Board, W.B.B.S.E) for year 2012 is not so far. Its coming.
Confusion with mathematics???
Don't worry . . .


Here is the suggestion for mathematics. Just download it. It will help you. (80-90% common.)
Lets download and solve the questions....


Link 1: Click here Or 
Link 2: Click here 


[ Note: The suggestion is free. Please don't use it for sale. If you satisfy with this . and anyone want to donate some money. call @ 9933714807 . ]



Best of luck for your exam.

or you can download the images from below.








  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

SEPERATING A STRING INTO TOKENS

There are many ways to split a line of text up into tokens. One simple example is to split up the words in a sentence. The following code shows how to do this using the strtok() function. Just beware that this function alters the original string, so if you need to use it again, make a copy before calling strtok().



#include
#include

#define DELIM " "
#define MAXWORD 80
#define MAXLEN 20

int main(void)
{
char words[MAXWORD][MAXLEN];
char buff[BUFSIZ];
int ntokens = 0;
int i;

printf("Enter a string: ");
fflush(stdout);

if (fgets(buff, sizeof buff, stdin) != NULL)
{
char *sep = strtok(buff, DELIM);

while (sep != NULL)
{
strcpy(words[ntokens++], sep);
sep = strtok(NULL, DELIM);
}
}

for (i = 0; i < ntokens; i++)
{
puts(words[i]);
}
return(0);
}
/** Output : Enter a string: this is a long line of text
this
is
a
long
line
of
text **/

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Jobs for Engineers ( 2011 Passout) 0-1 Years Exp

Post:Engineering Freshers

Experience: Freshers
Job Location: All India
Education: BE /B.TechGraduates( Electronics,Electrical, Instrumentation and Computer)
Desired Candidates Profile:
* 2011 pass out.
* Minimum 70% or above marks in 10th, 12th and BE.
* Good communication skills.

Note 1 : If Your are Eligible Kindly Post your Updated Resume to this E-Mail :- sgroupresume1@gmail.com for further Process. Mention the Designation "Engineering Freshers "which your Seeking in Subject of the Mail.

Note 2 :
Mention your Current Salary( CTC),Expected Salary (CTC),Notice Period, Current Employer,Current job location,contact number in your CV (Resume)

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Jobs for Software Engineers (2010 and 2011) Freshers / Exp

Industry: IT / Software / Telecom

Job Position : Fresher /Exp

1.Software Programmer
2.Software Developer
3.Trainee Programmer

Free Recruitment.No Any Fees( Like Service Charges / Recruitment Fees / Exam Fees)


Any Two (Skills) Subject / Working Knowledge must:


Skills:C, C++, VB,C#,Sharepoint,.NET,Java, J2EE,J2ME, J2SE, JSP, JBoss,JavaScript, JSP, PHP,Oracle(Forms, Reports, SQL/ PLSQL,Database design), ADO, Perl, HTML, Web services, SOAP, XML, ASP, MySQL, SQL Server, Oracle, UNIX, Linux, Redhat Linux, STL, XSLT, OWL, AJAX, Sun Solaris, Python, BEA WebLogic, WebSphere,

Male/Female

Fresh / Exp

Remuneration : Negotiable

Desired Qualification :


BE / B.Tech / MCA / ME / M.Tech / M.Sc,Any UG / PG /BCA/B.SC/Diploma Any
CS, IT, Software, EC, Telecom, EEE, EI, I&C, Indl Elec, Elec & Pow, M.Sc (CS, IT).
50% aggregate marks in 10th & 12th


Desired Experience : Freshers

Selection Process :

Written Test [1 hour 40 minutes].
Critical Incident reporting 30 minutes (The participants to fill in the Critical Incidents
Interviewee Form just after the Written Test).
Group Interview (GI): 45 minutes.
The one-on-one Interview : Critical Incident Interview (CI) and Technical Interview (TI) : 1 hr each.


Walk-In Venue : Details will be sent E mail to shortlisted candidates


Note 1 : If Your are Eligible Kindly Post y our Updated Resume to this E-Mail :- "itcareercv@gmail.com" for further Process. Mention the "Software Engineer " which your Seeking in Subject of the Mail.

Note 2 :Candidates other than the specified sector are welcome to update their resume specifying
their expected sector


Regards

HR Team-Head

Forward this to all your friends and relatives

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Introduction to Virtual Inheritance:

Inheritance is one of the most important concepts of object oriented programming and it is also present in C++ (added from Simula, where it was first invented in 1967).

Inheritance is used to create new classes, called derived classes, that inherit methods and properties from existing ones, called base classes. It provides a very efficient method of code reuse, giving the ability to create new classes that implement a common interface or use the functionality of an existing class in your own implementation. When more than one class fitting your implementation, you can join their functionality in your class by inheriting from all of them. This feature is allowed by the C++ standard and it's called multiple inheritance.



The diamond problem:

One of the problems that arises due to multiple inheritance is the diamond problem. A classical illustration of this is given by Bjarne Stroustrup (the creator of C++) in the following example:

class storable //this is the our base class inherited by transmitter and receiver classes
{
public:
storable(const char*);
virtual void read();
virtual void write();
virtual ~storable();
private:
....
}

class transmitter: public storable
{
public:
void write();
...
}

class receiver: public storable
{
public:
void read();
...
}

class radio: public transmitter, public receiver
{
public:
void read();
....
}



Since both transmitter and receiver classes are using the method write() from the base class, when calling the method write() from a radio object we are going to create an ambiguity--that is, the compiler can't know which implementation of write() to use, the one from the transmitter class or the one from the receiver class.

To understand how this is generated, let's take a look at how the objects are represented in memory. Inheritance simply puts the implementation of two objects one after another, but in this case radio is both a transmitter and a receiver, so the storable class gets duplicated inside the radio object. The g++ compiler will complain when compiling the code: error: 'request for member "write" is ambiguous', because it can't figure out either to get the method write() from storable::receiver::radio or from storable::transmitter::radio.

To prevent this behavior, C++ provides the virtual inheritance mechanism. In order to prevent the compiler from giving an error we use the keyword virtual when we inherit from the base class storable in both derived classes:



class transmitter: public virtual storable
{
public:
void read();
...
}

class receiver: public virtual storable
{
public:
void read();
...
}



Making the inheritance virtual will cause the compiler to provide a virtual function table (vtable) for classes transmitter and receiver, which will allow binding methods at run-time. By the way, the use of a vtable is also needed whenever virtual methods are declared, not only for virtual inheritance. The vtable is created in order to maintain the offset between the storable class and the beginning of transmitter/receiver for runtime binding. This will result in two new virtual pointers (vptr) in the memory layout of class radio, one pointing to the transmitter part and one to the receiver (there is a vptr for every virtual base class). Now the derived classes transmitter and receiver share the implementation of storable, making the implementation of radio unambiguous, and the code will compile fine.

The diamond problem is solved in many ways in different programming languages--for example, in Java and C#, full multiple inheritance is not allowed. Instead, they impose some constraints: allowing inheritance only from multiple interfaces (an interface is equivalent with an abstract base in C++, a class with virtual pure members).


Delegating to a sister class:

A powerful technique that arises from using virtual inheritance is to delegate a method from a class in another class by using a common abstract base class. This is also called cross delegation. Let's assume we have a similar scenario like in the diamond example, with small changes. Suppose the write() method in transmitter class needs to access the read() method from receiver for the radio to work (this is not a usual expected behavior, but let's suppose this for the sake of illustration) :


class storable
{
public:
storable(const char*);
virtual void read()=0; //this becomes pure virtual making storable an abstract
virtual void write(); //class
virtual ~storable();
private:
....
}

class transmitter: public virtual storable
{
public:
void write()
{
read();
....
}
}

class receiver: public virtual storable
{
public:
void read();
}

class radio: public transmitter, public receiver
{
public:
...
}

int main()
{
radio *rad = new radio();
receiver *r1 = rad;
transmitter *r2 =rad;

rad->write();
r1->write();
r2->write();
return 1;
}


Because of virtual inheritance, when the write() function from the transmitter class is called, the method read() from the receiver class gets called (as you may have noticed, the transmitter class doesn't have a read() function). In the above hierarchy we can instantiate only the radio class because transmitter and receiver are abstract due to virtual inheritance.


Other considerations when using multiple inheritance in C++:


When creating a derived object like radio, constructors from the hierarchy, the object is built in a specific order: first a pointer to the vtable is created and initialized, then the virtual base class constructor is run (but only once), then constructors from non-virtual bases are run, then the runtime calls constructors for the data members in the order they are declared, and finally, the body of the constructor is executed. In the case of destruction these steps are performed in reverse order--virtual base classes that appear in the hierarchy are destroyed last.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Bitwise Operators in C and C++:

Generally, as a programmer you don't need to concern yourself about operations at the bit level. You're free to think in bytes, or ints and doubles, or even higher level data types composed of a combination of these. But there are times when you'd like to be able to go to the level of an individual bit. Exclusive-or encryption is one example when you need bitwise operations.

Another example comes up when dealing with data compression: what if you wanted to compress a file? In principle, this means taking one representation and turning it into a representation that takes less space. One way of doing this is to use an encoding that takes less than 8 bits to store a byte. (For instance, if you knew that you would only be using the 26 letters of the Roman alphabet and didn't care about capitalization, you'd only need 5 bits to do it.) In order to encode and decode files compressed in this manner, you need to actually extract data at the bit level.

Finally, you can use bit operations to speed up your program or perform neat tricks. (This isn't always the best thing to do.)

Thinking about Bits

The byte is the lowest level at which we can access data; there's no "bit" type, and we can't ask for an individual bit. In fact, we can't even perform operations on a single bit -- every bitwise operator will be applied to, at a minimum, an entire byte at a time. This means we'll be considering the whole representation of a number whenever we talk about applying a bitwise operator. (Note that this doesn't mean we can't ever change only one bit at a time; it just means we have to be smart about how we do it.) Understanding what it means to apply a bitwise operator to an entire string of bits is probably easiest to see with the shifting operators. By convention, in C and C++ you can think about binary numbers as starting with the most significant bit to the left (i.e., 10000000 is 128, and 00000001 is 1). Regardless of underlying representation, you may treat this as true. As a consequence, the results of the left and right shift operators are not implementation dependent for unsigned numbers (for signed numbers, the right shift operator is implementation defined).

The leftshift operator is the equivalent of moving all the bits of a number a specified number of places to the left:
[variable]<<[number of places] 
For instance, consider the number 8 written in binary 00001000. If we wanted to shift it to the left 2 places, we'd end up with 00100000; everything is moved to the left two places, and zeros are added as padding. This is the number 32 -- in fact, left shifting is the equivalent of multiplying by a power of two.
int mult_by_pow_2(int number, int power) {     return number<Note that in this example, we're using integers, which are either 2 or 4 bytes, and that the operation gets applied to the entire sequence of 16 or 32 bits.

But what happens if we shift a number like 128 and we're only storing it in a single byte: 10000000? Well, 128 * 2 = 256, and we can't even store a number that big in a byte, so it shouldn't be surprising that the result is 00000000.

It shouldn't surprise you that there's a corresponding right-shift operator: >> (especially considering that I mentioned it earlier). Note that a bitwise right-shift will be the equivalent of integer division by 2.

Why is it integer division? Consider the number 5, in binary, 00000101. 5/2 is 2.5, but if you are performing integer division, 5/2 is 2. When you perform a right shift by one: (unsigned int)5>>1, you end up with 00000010, as the rightmost 1 gets shifted off the end; this is the representation of the number 2. Note that this only holds true for unsigned integers; otherwise, we are not guaranteed that the padding bits will be all 0s.

Generally, using the left and right shift operators will result in significantly faster code than calculating and then multiplying by a power of two. The shift operators will also be useful later when we look at how to manipulating individual bits.

For now, let's look at some of the other binary operators to see what they can do for us.

Bitwise AND

The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.

For instance, working with a byte (the char type):
01001000 &  10111000 =  -------- 00001000 
The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left. Consequently,
72 & 184 = 8 

Bitwise OR

Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||.
01001000 |  10111000 =  -------- 11111000 
and consequently
72 | 184 = 248 
Let's take a look at an example of when you could use just these four operators to do something potentially useful. Let's say that you wanted to keep track of certain boolean attributes about something -- for instance, you might have eight cars (!) and want to keep track of which are in use. Let's assign each of the cars a number from 0 to 7.

Since we have eight items, all we really need is a single byte, and we'll use each of its eight bits to indicate whether or not a car is in use. To do this, we'll declare a char called in_use, and set it to zero. (We'll assume that none of the cars are initially "in use".)
char in_use = 0; 
Now, how can we check to make sure that a particular car is free before we try to use it? Well, we need to isolate the one bit that corresponds to that car. The strategy is simple: use bitwise operators to ensure every bit of the result is zero except, possibly, for the bit we want to extract.

Consider trying to extract the fifth bit from the right of a number: XX?XXXXX We want to know what the question mark is, and we aren't concerned about the Xs. We'd like to be sure that the X bits don't interfere with our result, so we probably need to use a bitwise AND of some kind to make sure they are all zeros. What about the question mark? If it's a 1, and we take the bitwise AND of XX?XXXXX and 00100000, then the result will be 00100000:
XX1XXXXX &  00100000 =  -------- 00100000 
Whereas, if it's a zero, then the result will be 00000000:
XX0XXXXX &  00100000 =  -------- 00000000 
So we get a non-zero number if, and only if, the bit we're interested in is a 1.

This procedure works for finding the bit in the nth position. The only thing left to do is to create a number with only the one bit in the correct position turned on. These are just powers of two, so one approach might be to do something like:
int is_in_use(int car_num) {     // pow returns an int, but in_use will also be promoted to an int     // so it doesn't have any effect; we can think of this as an operation     // between chars     return in_use & pow(2, car_num); } 
While this function works, it can be confusing. It obscures the fact that what we want to do is shift a bit over a certain number of places, so that we have a number like 00100000 -- a couple of zeros, a one, and some more zeros. (The one could also be first or last -- 10000000 or 00000001.)

We can use a bitwise leftshift to accomplish this, and it'll be much faster to boot. If we start with the number 1, we are guaranteed to have only a single bit, and we know it's to the far-right. We'll keep in mind that car 0 will have its data stored in the rightmost bit, and car 7 will be the leftmost.
int is_in_use(int car_num) {     return in_use & 1<Note that shifting by zero places is a legal operation -- we'll just get back the same number we started with.

All we can do right now is check whether a car is in use; we can't actually set the in-use bit for it. There are two cases to consider: indicating a car is in use, and removing a car from use. In one case, we need to turn a bit on, and in the other, turn a bit off.

Let's tackle the problem of turning the bit on. What does this suggest we should do? If we have a bit set to zero, the only way we know right now to set it to 1 is to do a bitwise OR. Conveniently, if we perform a bitwise OR with only a single bit set to 1 (the rest are 0), then we won't affect the rest of the number because anything ORed with zero remains the same (1 OR 0 is 1, and 0 OR 0 is 0).

Again we need to move a single bit into the correct position: void set_in_use(int car_num) { in_use = in_use | 1<The Bitwise ComplementThe bitwise complement operator, the tilde, ~, flips every bit. A useful way to remember this is that the tilde is sometimes called a twiddle, and the bitwise complement twiddles every bit: if you have a 1, it's a 0, and if you have a 0, it's a 1.

This turns out to be a great way of finding the largest possible value for an unsigned number:
unsigned int max = ~0; 
0, of course, is all 0s: 00000000 00000000. Once we twiddle 0, we get all 1s: 11111111 11111111. Since max is an unsigned int, we don't have to worry about sign bits or twos complement. We know that all 1s is the largest possible number.

Note that ~ and ! cannot be used interchangeably. When you take the logical NOT of a non-zero number, you get 0 (FALSE). However, when you twiddle a non-zero number, the only time you'll get 0 is when every bit is turned on. (This non-equivalence principle holds true for bitwise AND too, unless you know that you are using strictly the numbers 1 and 0. For bitwise OR, to be certain that it would be equivalent, you'd need to make sure that the underlying representation of 0 is all zeros to use it interchangeably. But don't do that! It'll make your code harder to understand.)

Now that we have a way of flipping bits, we can start thinking about how to turn off a single bit. We know that we want to leave other bits unaffected, but that if we have a 1 in the given position, we want it to be a 0. Take some time to think about how to do this before reading further.

We need to come up with a sequence of operations that leaves 1s and 0s in the non-target position unaffected; before, we used a bitwise OR, but we can also use a bitwise AND. 1 AND 1 is 1, and 0 AND 1 is 0. Now, to turn off a bit, we just need to AND it with 0: 1 AND 0 is 0. So if we want to indicate that car 2 is no longer in use, we want to take the bitwise AND of XXXXX1XX with 11111011.

How can we get that number? This is where the ability to take the complement of a number comes in handy: we already know how to turn a single bit on. If we turn one bit on and take the complement of the number, we get every bit on except that bit:
~(1<Now that we have this, we can just take the bitwise AND of this with the current field of cars, and the only bit we'll change is the one of the car_num we're interested in.
int set_unused(int car_num) {     in_use = in_use & ~(1<You might be thinking to yourself, but this is kind of clunky. We actually need to know whether a car is in use or not (if the bit is on or off) before we can know which function to call. While this isn't necessarily a bad thing, it means that we do need to know a little bit about what's going on. There is an easier way, but first we need the last bitwise operator: exclusive-or.

Bitwise Exclusive-Or (XOR)

There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a carrot, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR.

For instance, if you have two numbers represented in binary as 10101010 and 01110010 then taking the bitwise XOR results in 11011000. It's easier to see this if the bits are lined up correctly:
01110010 ^ 10101010  -------- 11011000 
You can think of XOR in the following way: you have some bit, either 1 or 0, that we'll call A. When you take A XOR 0, then you always get A back: if A is 1, you get 1, and if A is 0, you get 0. On the other hand, when you take A XOR 1, you flip A. If A is 0, you get 1; if A is 1, you get 0.

So you can think of the XOR operation as a sort of selective twiddle: if you apply XOR to two numbers, one of which is all 1s, you get the equivalent of a twiddle.

Additionally, if you apply the XOR operation twice -- say you have a bit, A, and another bit B, and you set C equal to A XOR B, and then take C XOR B: you get A XOR B XOR B, which essentially either flips every bit of A twice, or never flips the bit, so you just get back A. (You can also think of B XOR B as cancelling out.) As an exercise, can you think of a way to use this to exchange two integer variables without a temporary variable? (Once you've figured it out, check the solution.)

How does that help us? Well, remember the first principle: XORing a bit with 0 results in the same bit. So what we'd really like to be able to do is just call one function that flips the bit of the car we're interested in -- it doesn't matter if it's being turned on or turned off -- and leaves the rest of the bits unchanged.

This sounds an awful lot like the what we've done in the past; in fact, we only need to make one change to our function to turn a bit on. Instead of using a bitwise OR, we use a bitwise XOR. This leaves everything unchanged, but flips the bit instead of always turning it on:
void flip_use_state(int car_num) {     in_use = in_use ^ 1<

When should you use bitwise operators?

Bitwise operators are good for saving space -- but many times, space is hardly an issue. And one problem with working at the level of the individual bits is that if you decide you need more space or want to save some time -- for instance, if we needed to store information about 9 cars instead of 8 -- then you might have to redesign large portions of your program. On the other hand, sometimes you can use bitwise operators to cleverly remove dependencies, such as by using ~0 to find the largest possible integer. And bit shifting to multiply by two is a fairly common operation, so it doesn't affect readability in the way that advanced use of bit manipulation can in some cases (for instance, using XOR to switch the values stored in two variables).

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Windows Graphics & OpenGL

Introduction to C++ OpenGL Programming:

Welcome to another fine lesson in C++! Today you'll be introduced to the wonderful world of OpenGL. OpenGL is a fairly straight forward -- although at many times confusing -- concept. OpenGL gives the programmer an interface with the graphics hardware. OpenGL is a low-level, widely supported modeling and rendering software package, available on all platforms. It can be used in a range of graphics applications, such as games, CAD design, or modeling (to name a few).

OpenGL is the core graphics rendering option for many 3D games, such as Quake 3. The providing of only low-level rendering routines is fully intentional because this gives the programmer a great control and flexibility in his applications. These routines can easily be used to build high-level rendering and modeling libraries. The OpenGL Utility Library (GLU) does exactly this, and is included in most OpenGL distributions!

Unlike DirectX, OpenGL is only a graphics API; it doesn't include support for functionality such as sound, input, or networking (or anything not related to graphics). That's ok, however, because in future tutorials I will teach you how you how to use DirectX for these things.

OpenGL was originally developed in 1992 by Silicon Graphics, Inc, (SGI) as a multi-purpose, platform independent graphics API. Since 1992 all of the development of OpenGL has been headed by the OpenGL Architecture Review Board (ARB). This exclusive board is composed of the major graphics vendors and industry leaders. Some of these are Intel, IBM, NVIDIA, Microsoft, and Silicon Graphics.

OpenGL is a collection of several hundred functions that provide access to all of the features that your graphics hardware has to offer. Internally it acts like a state machine-a collection of states that tell OpenGL what to do. Using the API you can set various aspects of this state machine, including current color, blending, lighting effect, etc.

This is a very general introduction to OpenGL, and you may find other in-depth introductions elsewhere. There is a reason, however, to my generalized introduction. I don't want to slam you with specifics, but give you an idea as to what OpenGL is so that you may decide for yourself if this set of lessons is for you.


OpenGL vs. DirectX: A Comparison:

The competition between OpenGL and DirectX is possibly as well known as the wars waged between AMD and Intel enthusiasts. This topic has sparked the fires of many flame wars throughout the years, and I don't anticipate that changing anytime soon. I won't preach why I prefer OpenGL over DirectX, but rather lay out the facts and let you make that decision. So let's dive in!

Perhaps the most obvious difference is that DirectX, as opposed to OpenGL, is more than just a graphics API. DirectX contains tools to deal with such components of a game as sound, music, input, networking, and multimedia. On the other hand, OpenGL is strictly a graphics API. So what aspect of OpenGL sets it apart from the DirectX graphics component?

Well, first things first: both APIs rely on the use of the traditional graphics pipeline. This is the same pipeline that has been used in computer games since the early days of computer graphics. Although it has been modified in slight ways to adapt with advancements in hardware, the basic idea remains intact.

Both OpenGL and DirectX describe vertices as a set of data consisting of coordinates in space that define the vertex location and any other vertex related data. Graphics primitives, such as points, lines, and triangles, are defined as an ordered set of vertices. There is a difference in how each API handles how vertices are combined to form primitives.

There are a bunch of differences in the DirectX and OpenGL APIs, so I will list a few of those for you. This chart is based off the book, OpenGL Game Programming and a few of these may now be incorrect as new DirectX versions are released. If you wish to correct me, please do via one of the ways listed at the end of this tutorial.

Table 1.1:
Feature: OpenGL DirectX
Vertex Blending N/A Yes
Multiple Operating Systems Yes No
Extension Mechanism Yes Yes
Development Multiple member Board Microsoft
Thorough Specification Yes No
Two-sided lighting Yes No
Volume Textures Yes No
Hardware independent Z-buffers Yes No
Accumulation buffers Yes No
Full-screen Antialiasing Yes Yes
Motion Blur Yes Yes
Depth of field Yes Yes
Stereo Rendering Yes No
Point-size/line-width attributes Yes No
Picking Yes No
Parametric curves and surfaces Yes No
Cache geometry Display Lists Vertex Buffers
System emulation Hardware not present Let app determine
Interface Procedure calls COM
Updates Yearly Yearly
Source Code Sample SDK Implementation

So now you know what separates DirectX and OpenGL, and hopefully you have chosen based on facts which you would prefer, not on myths or opinions.


Introduction to Windows Programming and OpenGL:



At this time we will take a look into the vast world of Windows programming. Since this tutorial is based entirely on programming done within the Windows environment, it will be required of you to have access to a Windows machine and compiler such as Code::Blocks.


For the programs we will be creating you will need a base understanding of the mechanics and structuring of the Windows operating system. Not to worry, however, because I am going to teach this to you!

Microsoft Windows is a multi-tasking operating system that allows multiple applications, referred to here on out as processes. Every process in Windows is given a certain amount of time, called a time slice, where the application is given the right to control the system without being interrupted by the other processes. The runtime priority and the amount of time allocated to a process are determined by the scheduler.

The scheduler is, simply put, the manager of this multi-tasking operating system, ensuring that each process is given the time and the priority it needs depending on the current state of the system.

When it comes to game developers, you will find a large common interest in multithreading. Processes can be broken down into threads, where each thread can execute its own code to allow for multitasking within a single application. The scheduling for threads is the same as that for processes, except that threads are what make up the process.

This means that within your games you can have multiple threads running that can perform multiple calculations at once and thus provide your game with multitasking within itself. To go a step farther we can do a quick explanation of fibers. In newer versions of Windows (Windows 98+) there is an even lower level execution object exists, called a fiber. Each thread in your process has the ability to house multiple fibers that can perform multiple operations at once, all in a single thread.

Windows is what is known as an event-driven operating system. What this means is that each process is executed based on the events they receive from the operating system. For instance, an application may sit at idle and wait for the user to press a key. When that key is pressed Windows will register an event to the application that the key is down.

Windows programming is difficult at all in most cases, and to start we'll use the most basic program ever created. Hello World is used in almost every class when you begin programming in any language, and that won't change here. So, shall we have a look at Hello World in Windows style? Sure!


#include  int APIENTRY WinMain(HINSTANCE hInstance,                      HINSTANCE hPrevInstance,                      LPSTR     lpCmdLine,                      int       nCmdShow) {     MessageBox(NULL, "\tHello World!", "My first windows app", NULL);  return 0; }


As you can see, it's pretty straight forward. Don't pay attention to the things that don't make sense, as in the next lesson we will go in-depth to explain WinMain () and other functions, as well as show how this and OpenGL work together!


WinMain() and the Windows Procedure:

Every Windows programming needs a main entry point. That being said, you may be wondering what this entry point is. The main entry point for any Windows program is called WinMain. The function prototype for WinMain is a little confusing at first, but as we continue to work with it you'll notice it becomes much easier to understand. Well. we've told you what it is; now were going to show you! Here's the prototype for WinMain:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd);


As you may have already noticed, the return type for WinMain is, and always will be, int. All 32-bit Windows operating system uses the calling convention WINAPI. This calling convention MUST be used to distinguish the function as the entry point. Now for the parameters. As you can see, WinMain uses four parameters when the program starts. Let's have a look at them, shall we?
hInstance - is a handle to your applications instance, where an instance  can be considered to be a single run of your application. The instance  is used by windows as a reference to your application for event handling, message processing, and various other duties. hPrevInstance - is always NULL.  lpCmdLine - is a pointer string that is used to hold any command-line arguments that may have been specified when the application began.   For example, if the user opened the Run application and typed myapp.exe myparameter 1, then lpCmdLine would be myparameter 1. nShowCMD - is the parameter that determines how your application's window will be displayed once it begins executing. 
Pretty simple, right? Don't worry if it's confusing, it will make sense soon enough! The Windows program you create is going to need some way to handle the messages that Windows will send to it. A few examples of these messages are: WM_CREATE, WM_SIZE, and WM_MOVE. There are TONS of these messages, and we'll show you how to handle a large number of them. To allow Windows to communicate with your application, we'll create a dandy little function called a Windows procedure. This most common name for this function is WndProc. This function MUST be created and used to determine how your application will respond to various events. The Windows procedure may also be called the event handler because, well, it responds to Windows events! So let's have a quick look at the prototype:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); 
This function is declared with a return type of LRESULT CALLBACK. The LRESULT type is used by Windows to declare a long integer, and CALLBACK is a calling convention used with functions that are called by Windows. The Windows Procedure is a function pointer, which allows you to call it whatever you want because the function's address will be assigned as a function pointer upon creation of the window class.
hwnd - Only important if you have several windows of the same class open at one time. This is used to determine which window hwnd pointed to before  deciding on an action. message - The actual message identifier that WndProc will be handling. wParam and lParam - Extensions of the message parameter. Used to give  more information and point to specifics that message cannot on its own. 
Well now you should have a better understanding of these two topics. You may be wondering when you get to see some openGL usage, and the answer is soon. We first need to cover the basics, let's remember, we're here to learn!


First Windows Application:


The following code is a build up on the basic "hello world" program I showed you earlier. Take a minute to review it, maybe even key it into your compiler and run it, and then we will break it down so that it is easier to understand what is actually going on.

/* Trim fat from windows*/ #define WIN32_LEAN_AND_MEAN  #pragma comment(linker, "/subsystem:windows") /* Pre-processor directives*/ #include "stdafx.h" #include  /* Windows Procedure Event Handler*/ LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {  PAINTSTRUCT paintStruct;  /* Device Context*/  HDC hDC;   /* Text for display*/  char string[] = "Hello, World!";   /* Switch message, condition that is met will execute*/  switch(message)  {   /* Window is being created*/   case WM_CREATE:     return 0;    break;   /* Window is closing*/   case WM_CLOSE:     PostQuitMessage(0);    return 0;    break;   /* Window needs update*/   case WM_PAINT:     hDC = BeginPaint(hwnd,&paintStruct);    /* Set txt color to blue*/    SetTextColor(hDC, COLORREF(0x00FF0000));    /* Display text in middle of window*/    TextOut(hDC,150,150,string,sizeof(string)-1);    EndPaint(hwnd, &paintStruct);    return 0;    break;   default:    break;  }  return (DefWindowProc(hwnd,message,wParam,lParam)); } /* Main function*/ int APIENTRY WinMain(HINSTANCE hInstance,                      HINSTANCE hPrevInstance,                      LPSTR     lpCmdLine,                      int       nCmdShow) {  WNDCLASSEX  windowClass;  //window class  HWND  hwnd;    //window handle  MSG   msg;    //message  bool  done;    //flag saying when app is complete  /* Fill out the window class structure*/  windowClass.cbSize = sizeof(WNDCLASSEX);  windowClass.style = CS_HREDRAW | CS_VREDRAW;  windowClass.lpfnWndProc = WndProc;  windowClass.cbClsExtra = 0;  windowClass.cbWndExtra = 0;  windowClass.hInstance = hInstance;  windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);  windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);  windowClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);  windowClass.lpszMenuName = NULL;  windowClass.lpszClassName = "MyClass";  windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);  /* Register window class*/  if (!RegisterClassEx(&windowClass))  {   return 0;  }  /* Class registerd, so now create window*/  hwnd = CreateWindowEx(NULL,  //extended style   "MyClass",   //class name   "A Real Win App",  //app name   WS_OVERLAPPEDWINDOW |  //window style   WS_VISIBLE |   WS_SYSMENU,   100,100,   //x/y coords   400,400,   //width,height   NULL,    //handle to parent   NULL,    //handle to menu   hInstance,   //application instance   NULL);    //no extra parameter's  /* Check if window creation failed*/  if (!hwnd)   return 0;  done = false; //initialize loop condition variable  /* main message loop*/  while(!done)  {   PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE);   if (msg.message == WM_QUIT) //check for a quit message   {    done = true; //if found, quit app   }   else   {    /* Translate and dispatch to event queue*/    TranslateMessage(&msg);     DispatchMessage(&msg);   }  }  return msg.wParam; } 
Well isn't this a whole mess of code! The first thing that you may have noticed is #define WIN32_LEAN_AND_MEAN. This syntax prevents Visual C++ from linking modules that you aren't going to need in your application.

Moving on we come to the include line #include . This includes all the headers you need in this application. Sometimes you may want to include , which will give you a few useful macros to use in Windows development.

The first function we arrive at is the WndProc function. We've discussed this before, so I am just going to highlight two lines I have added here.
HDC hDC;    //device context Char string[] = "Hello World!"; //display text 
These two lines are essential as they declare the device context that we are going to use to output to the window we create, and the string that we will display. As we continue on in the code we arrive at the switch statement. This switch is used to determine the message being passed to the windows procedure. In this particular instance we want to take a closer look at the WM_PAINT block.
case WM_PAINT:     hDC = BeginPaint(hwnd,&paintStruct);    /* Set txt color to blue*/    SetTextColor(hDC, COLORREF(0x00FF0000));    /* Display text in middle of window*/    TextOut(hDC,150,150,string,sizeof(string)-1);    EndPaint(hwnd, &paintStruct);    return 0;    break; 
When the window is moved, resized, or is otherwise changed the window needs to be updated. The first noticeable change here is the use of the hDC device context. The win32 function BeginPaint() returns the graphics device context for the hwnd passed to it. You can then use this hDC to set the text color with SetTextColor() and follow up with the TextOut() function to display the text. If you want to know more about these functions, check out MSDN.

Next function up is the WinMain() function. Most of the WinMain() content is pretty straight forward, but were going to review a few parts of it for good measure. The msg variable holds the message received by PeekMessage() from the queue, and will be sent to TranslateMessage() and DispatchMessage(). The variable done is a Boolean value used by your message loop and will not equal true until a WM_QUIT message has been received from the queue to indicate that the application is about to be closed.

For easier understanding we will break the order of each setup task into a list.
1. Window-class setup 2. Window-class registration 3. Window Creation 4. Message loop with event handler 
We now have a fully working Windows application! I encourage you to toy around with the code and alter it to your liking. Don't be discouraged by errors or problems, for it is these things that make us better.



WGL and the Wiggle Functions in C++:



The simple fact that OpenGL is only a graphics API means that any user interaction, or things like screen and window issues needs to be handled by the operating system. Most operating systems come with a set of extensions that tie OpenGL together with user interaction and window management. This tends to make our lives a little bit easier, but only if we know how to take advantage of this option. In Windows this set of functions are called the wiggle functions. Each of these functions is prefixed with wgl.

To maintain the portability of OpenGL, each operating system must supply functionality for specifying the rendering window before OpenGL can use it. In Windows the Graphics Device Interface uses a device context to remember settings about drawing modes and commands, but in OpenGL the rendering context is used to remember these things. You need to remember, however, that the device context is not a rendering context. The device context MUST be specified in a GDI call, unlike a rendering context, which is specified in an OpenGL call.

If you wish to render more than one window at once, multiple rendering contexts are allowed. You must ensure, however, that the proper rendering context is being used on the proper window. Another thing to remember is that OpenGL is thread-safe. You can have multiple threads rendering to the same device context at one time.

As I mentioned to you earlier, wiggle functions bring Windows API support into OpenGL. Well let's take this time to have a look at a few common wiggle functions:
  • wglCreateContext();
  • wglDeleteContext();
  • wglMakeCurrent();
The wglCreateContext() function creates a handle to the OpenGL rendering context while being passed like a handle to a GDI device context. The correct prototype for this function is:
 HGLRC wglCreateContext(HDC hDC); 
This function should only be called after the pixel format for the device context has been set. Don't worry, pixel format is coming into teaching shortly.

Keep in mind that as with a device context, a rendering context must be deleted after you are finished with it. This is where the wglDeleteContext() function comes into play. Let's have a look at the prototype for good measure:
 BOOL  wglDeleteContext(HGLRC hRC); 
The name wglMakeCurrent() is highly accurate to what the function does. The function makes the rendering context passed to it the current rendering context. Makes a lot of sense, doesn't it? The device context used must have the same pixel format characteristics as the device context that was used to create the rendering context. This means that the device context used to create the rendering context does not need to be the same as the device context assigned to the wglMakeCurrent() function. Without further delay, let's see the prototype!
 BOOL  wglMakeCurrent(HDC hDC, HGLRC hRC); 
You need to ensure that the device context and the rendering context passed to the function have the same pixel format, or the function will not work. To deselect the rendering context you can simply pass NULL for the hRC parameter, or simply pass another rendering context.

Both the wglCreateContext() and the wglMakeCurrent() functions should be called upon window creation. Let's look at a code snippet for an example of these in use:
LRESULT CALLBACK WndProc (HWND hwnd, UNIT message, WPARAM wParam, LPARAM lParam) {  static HGLRC hRC; //rendering context  static HDC hDC; //device context  switch (message)  {  case WM_CREATE:  hDC = GetDC(hwnd); //get the device context for window  hRC = wglCreateContext(hDC); //create rendering context  wglMakeCurrent(hDC,hRC); //make rendering context current  break;  case WM_DESTROY:  wglMakeCurrent(hDC,NULL); //deselect rendering context  wglDeleteContext(hRC);  //delete rendering context  PostQuitMessage(0);  //send wm_quit  break;  } } 
This code creates and destroys your OpenGL window.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS