Difference between revisions of "Bit.band"

From ComputerCraft Wiki
Jump to: navigation, search
(You don't need to sign articles.)
m (Changed nonexistent type int to type number.)
 
(4 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{stub}}
+
{{lowercase}}
 +
{{Function
 +
|name=bit.band
 +
|args={{Type|number}} m, {{Type|number}} n
 +
|api=bit
 +
|returns={{Type|number}} the value of <var>m</var> AND <var>n</var>
 +
|addon=ComputerCraft
 +
|desc=Computes the bitwise AND of two numbers
 +
|examples=
 +
{{Example
 +
|desc=AND the number 18 (10010) with the number 3 (00011), yielding 2 (00010)
 +
|code=print(bit.band(18, 3))
 +
|output=2
 +
}}
 +
}}
 +
 
 
== Explanation ==
 
== Explanation ==
''AND'' is a gate that is only on when both inputs are on. (ex. (0,0)=0; (1,0)=0; (0,1)=0; (1,1)=1)
+
All bit operations operate in binary numeral system [http://en.wikipedia.org/wiki/Binary_numeral_system]. An AND operation between two bits yields a 1 if the bits are both 1 and a 0 if either of the bits is 0. This function produces an output by computing the AND of each bit of its two inputs independently. So, for the example above:
 +
 
 +
{| class="wikitable"
 +
|-
 +
! Bit index:
 +
| 4
 +
| 3
 +
| 2
 +
| 1
 +
| 0
 +
|-
 +
! Input 1 (18):
 +
| 1
 +
| 0
 +
| 0
 +
| 1
 +
| 0
 +
|-
 +
! Input 2 (3):
 +
| 0
 +
| 0
 +
| 0
 +
| 1
 +
| 1
 +
|-
 +
! Calculation:
 +
| 3 has a 0
 +
| Both 0
 +
| Both 0
 +
| Both 1
 +
| 18 has a 0
 +
|-
 +
! Output (2):
 +
| 0
 +
| 0
 +
| 0
 +
| 1
 +
| 0
 +
|}
  
== Other than Binary ==
+
[[Category:API_Functions]]
''AND'' can be used as a basic ''if equals' command, but isn't very reliable due to its behavior. When the lowest number is even and you count up it will pulse that number for as many times as that number. (ex. if 2 is the lowest number: 2=2 3=2, 4=0, 5=0, 6=2, 7=2, 8=0, 9=0, 10=2, 11=2, 12=0) However, if the lowest number is odd it will count up to that number then return to zero and start again. (ex. if you use 3 you get: 4=0, 5=1, 6=2, 7=3, 8=0, 9=1, 10=2, 11=3, 12=0)
+

Latest revision as of 01:36, 12 July 2013


Grid Redstone.png  Function bit.band
Computes the bitwise AND of two numbers
Syntax bit.band(number m, number n)
Returns number the value of m AND n
Part of ComputerCraft
API bit

Examples

Grid paper.png  Example
AND the number 18 (10010) with the number 3 (00011), yielding 2 (00010)
Code
print(bit.band(18, 3))
Output 2


Explanation

All bit operations operate in binary numeral system [1]. An AND operation between two bits yields a 1 if the bits are both 1 and a 0 if either of the bits is 0. This function produces an output by computing the AND of each bit of its two inputs independently. So, for the example above:

Bit index: 4 3 2 1 0
Input 1 (18): 1 0 0 1 0
Input 2 (3): 0 0 0 1 1
Calculation: 3 has a 0 Both 0 Both 0 Both 1 18 has a 0
Output (2): 0 0 0 1 0