Skip to content

Commit fb1d05a

Browse files
authored
Update 671-language-nand.markdown
1 parent 9df3f0c commit fb1d05a

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed
Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
11
# NAND
22

3-
> a NAND b
3+
> y = a NAND b
44
55
Bitwise exclusive NOT AND.
66

7+
Truth table:
78

8-
~~~
9+
| a | b | a NAND b |
10+
|:-:|:-:|:--------:|
11+
|0 | 0 | 1 |
12+
|0 | 1 | 1 |
13+
|1 | 0 | 1 |
14+
|1 | 1 | 0 |
915

16+
17+
### Example 1
18+
19+
The NOT-operation as part of NAND performs a bitwise inversion on all bits of a number. This leads to the following (maybe unexpected) result:
20+
21+
```
22+
print 1 NAND 1 ' Output: 11111111111111111111111111111110
23+
```
24+
25+
### Example 2: Operate NAND only on last n bits
26+
27+
If you want to operate NAND only on the last `n` bits of the numbers, you can use the following code:
28+
29+
```
30+
n = 4
31+
a = 0b1101
32+
b = 0b1001
33+
34+
print bin((a NAND b) BAND ((1 lshift n ) - 1))
35+
36+
' Output 110
37+
```
38+
39+
### Example 3: Two's complement
40+
41+
> Two's complement is a mathematical operation to reversibly convert
42+
> a positive binary number into a negative binary number with equivalent negative value. ([Wikipedia](https://en.wikipedia.org/wiki/Two%27s_complement))
43+
44+
```
1045
' Two's complement is the standard way of representing negative integers in binary.
1146
' The sign is changed by inverting all of the bits and adding one.
12-
Def invsgn(n) = ((n Nand n) + 1) - Frac(n) ' invert the sign of n
47+
48+
Def invsgn(n) = ((n Nand n) + 1) - Frac(n) ' invert the sign of n
49+
1350
While True Do
1451
Input "Enter a number (Enter empty to stop) : ", n
1552
If Isstring(n) Then
@@ -19,7 +56,7 @@ While True Do
1956
Print "This is the number with inverted sign: "; invsgn(n)
2057
Print
2158
Wend
59+
```
2260

23-
~~~
2461

2562

0 commit comments

Comments
 (0)