0

so if I have x = 0x01 and y = 0xff and I do x & y, I would get 0x01. If I do x && y do I still get 0x01, but the computer just says its true if its anything than 0x00? My question is are the bits the same after the operation regardless of bit-wise or logical AND/OR, but the computer just interprets the final result differently? In other words are the hex values of the result of & and && (likewise | and ||) operations the same?

edit: talking about C here

Tommy K
  • 1,759
  • 3
  • 28
  • 51

2 Answers2

1

The answer depends on the precise language in use.

In some weakly-typed languages (e.g. Perl, JavaScript) a && b will evaluate to the actual value of b if both a and b are "truthy", or a otherwise.

In C and C++ the && operator will just return 0 or 1, i.e. the int equivalent of true or false.

In Java and C# it's not even legal to supply an int to && - the operands must already be booleans.

I don't know of any language off the top of my head where a && b == a & b for all legal values of a and b.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • This particular question if for C. I have a question where I have to fill the hex values for a given x and y(mask). So even if I have `x = 0x0a && y = 0x7`, the result will be 0x01? Not 0x06? I thought with && its false if 0 and true if anything else – Tommy K Feb 02 '15 at 17:03
  • Yup, it'll be `0x01`, that is `(int)true` – Alnitak Feb 02 '15 at 17:08
0

In C#, the operators behave differently: && is only allowed for boolean types and & for any integer type as well.

a && b returns true, if both a and b are true. a & b returns the result of the bitwise AND operation.