- Home /
How do I compare two binary values in Javascript?
Consider that I have an 8 bit number, let's say 00101101, and I want to check whether the third bit from the right is one or zero.
I imagine could do ( 00101101 AND 00000100 ), and if the result is anything other than zero I would know that bit 3's value is one. Is there a way to do this in Unity? Is there a different way than the one I'm proposing?
I imagine this must be very simple, but I can't find any reference in the docs. Thanks!
P.S. The reason I'm doing this is for a tiling system. I need to adjust some mesh colliders based on their surroundings. Without this kind of binary comparison the code is becoming too unwieldy, very long and with tons of special cases. I believe I can simplify things a bit if this is possible.
Answer by CHPedersen · Aug 11, 2014 at 08:38 AM
Your approach is exactly right, and you just need to use the binary logical AND operator, which is a single ampersand "&", not to be confused with the conditional AND, which is far more common and a double ampersand "&&". There is information about this operator, and more, on MSDN:
http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
A small code sample:
byte number = 0x2D; // 00101101
byte mask = 4; // 00000100
bool thirdBitOne = (number & mask) > 0;
Awesome! I didn't know about the single ampersand.
One more thing, though: can I provide the numbers in binary form? I could write a function for that, but if there's a native way to do it would be better. Thanks!!!
(Converted your answer to comment.)
You cannot provide numbers in binary form, unfortunately. This would be called "binary literals", and is not supported in .Net. $$anonymous$$icrosoft will provide support for it C# 6.0 but this version is not yet released, and there is no telling when Unity's $$anonymous$$ono version will catch up to $$anonymous$$icrosoft's compiler level.
When it does happen, however, you could probably declare them like this:
byte binaryLiteral = 0b10101010;
No problem, this will work great.
The operator seems to work well with decimal values as well, so for each tile surrounding the current one I'll assign a power of two value (1, 2, 4, etc.), and their sum will give me a byte that represents the surrounding configuration.Thanks!
Has this changed since 2011? can i do:"
var v1 = 1000;
var v2 = 2000;
if( (v1 & v2) = 0) print ( "different numbers");
Your answer
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Maths with variables 2 Answers
Calculations Wrong? 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers