Question : binary example

can you provide a simple example to understanding the purpose and usefulness of the above data type?

thanks

Answer : binary example

Here's an everyday, programming example.  

Let's say you want a single integer variable to store zero, one, or more flags, that is, indications of state.  For example, let's say you were developing a program that returned an char which indicates what buttons are pressed on a joystick.  

You would need to be able to add together the values of these flags, without destroying the individual values of each.  Let's try doing that incrementally.  Button 1 is 1, button 2 is 2, button 3 is 3, etc.  

But wait, there's a problem!  If we return 3, how can we tell whether we're pushing buttons 1 and 2, or just button 3?  There's no way, so we have to find some other way to express the values.  

Let's try tens.  Button 1 is 1, button 2 is 10, button 3 is 100, and so on.  That'll work just fine!  We can easily determine that 100 is button 3, or that 11 is buttons 1 and 2!

But we have another problem.  Let's say that the joystick has 5 buttons, but we have to return a char data type.  Char only goes up to 255, so we only have room for 3 buttons!  Help!

The solution:  Think binary.  With binary, we can use the tens method, but without using as much space.  Binary works with powers of 2.  So button 1 would be 1, button 2 would be 2, button 3 would be 4, button 4 would be 8 and so forth.  If you expressed the previous values in binary, they'd be 1, 10, 100, and 1000 respectively.  But to have 5 buttons, we'd only need to go up to the number 16, which is well within the parameters for the char data type.  Problem solved.  

I'm a huge advocate of tech people learning the binary number system, as it provides a deeper understanding into many ways of how computers work, and it can also solve problems like the one shown above.  I hope I've convinced you that binary is useful!
Random Solutions  
 
programming4us programming4us