2

The variable 'format' is a byte and the javascript reads like:

  if( format & 2 ) // have normals
    {
        var normals = new Vector3[vertCount];
        ReadVector3ArrayBytes (normals, buf);
        mesh.normals = normals;
    }

Source here: http://wiki.unity3d.com/index.php?title=MeshSerializer2

C# complains about this and says it cannot implicitly convert an int to a bool.

What does format & 2 accomplish and what should I be checking for in C# to evaluate if it's true? Also some further reading material on the matter would be helpful..

derHugo
  • 83,094
  • 9
  • 75
  • 115
meds
  • 21,699
  • 37
  • 163
  • 314
  • And operator in c# is &&. – thefern Oct 12 '14 at 12:38
  • @fredz0003: That's the short circuit version, and it only works for boolean operands. The `&` operator is the non short-circuit version for boolean operands, and the bitwise operator for numeric operands. – Guffa Oct 12 '14 at 12:49

3 Answers3

3

The & operator in Javascript is the bitwise and operator (ref: bitwise operators).

A bitwise and operation with 2 will give the value 0 or 2 depending on whether the second bit was set in the other operand. Example:

format    01101010
2         00000010
& ----------------
=         00000010

In Javascript you can use any value as a condition in an if statement, and it will be interpreted as a boolean value. For numeric values any non-zero (and not NaN) value will be considered as true.

In C# the & operator also works as a bitwise and operator when applied to integers. There is no automatic conversion to a boolean value, so you have to check the result of the bitwise operation to get a condition:

if ((format & 2) != 0)
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • @soshiki bits and bitwise operators are often used in C# to implement small [sets](http://en.wikipedia.org/wiki/Set_(abstract_data_type)) using enums. For further reading see [Stack Overflow: What does the Flags Enum Attribute mean in C#?](http://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c) and [James Michael Hare: C# Fundamentals: Combining Enum Values with Bit-Flags](http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx) – xmojmr Oct 13 '14 at 16:46
2

I think it is bit-wise operation which checks is set the second bit of byte. (2 isn't number of bit, just 10 is 2 in base 2).

if((format & 2) != 0)
{
    ..
}

or

if((format & 2) == 2)
{
    ..
}
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
1

The & is used for bitwise and operations.

The | is used for bitwise or operations.

You can only use these on integers.


Simple example to get you to understand it:

var r : int;
r = Random.Range(0, 1000);

if(r & 1)
    // Odd.

else
    // Even.
apxcode
  • 7,696
  • 7
  • 30
  • 41