Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why AND two numbers to get a Boolean?

Tags:

c#

vb.net

digital

I am working on a little Hardware interface project based on the Velleman k8055 board.

The example code comes in VB.Net and I'm rewriting this into C#, mostly to have a chance to step through the code and make sense of it all.

One thing has me baffled though:

At one stage they read all digital inputs and then set a checkbox based on the answer to the read digital inputs (which come back in an Integer) and then they AND this with a number:

i = ReadAllDigital
cbi(1).Checked = (i And 1)
cbi(2).Checked = (i And 2) \ 2
cbi(3).Checked = (i And 4) \ 4
cbi(4).Checked = (i And 8) \ 8
cbi(5).Checked = (i And 16) \ 16

I have not done Digital systems in a while and I understand what they are trying to do but what effect would it have to AND two numbers? Doesn't everything above 0 equate to true?

How would you translate this to C#?

like image 451
Gineer Avatar asked Apr 27 '09 08:04

Gineer


People also ask

What type of operators are used to join two Boolean values?

The most commonly used Boolean Operators are AND, OR, and NOT.

When evaluating two Boolean conditions the OR operator signifies what result?

The “OR” operator is represented with two vertical line symbols: result = a || b; In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true , it returns true , otherwise it returns false .

What is default Boolean value in C#?

The default value of the bool type is false .


1 Answers

This is doing a bitwise AND, not a logical AND.

Each of those basically determines whether a single bit in i is set, for instance:

5 AND 4 = 4
5 AND 2 = 0
5 AND 1 = 1

(Because 5 = binary 101, and 4, 2 and 1 are the decimal values of binary 100, 010 and 001 respectively.)

like image 110
Jon Skeet Avatar answered Oct 11 '22 17:10

Jon Skeet