From 68e7028aab121412c5dd172317fef6a06d6f8ace Mon Sep 17 00:00:00 2001 From: Krinjih Date: Mon, 19 Nov 2018 03:51:17 +0100 Subject: [PATCH] Added examples for logic operators (#22259) * Added examples for logic operators Added tables for examples for "and", "or" and "xor" * fixed table formatting --- guide/english/c/more-math/index.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/guide/english/c/more-math/index.md b/guide/english/c/more-math/index.md index aba929dcc4..7f3fa04e67 100644 --- a/guide/english/c/more-math/index.md +++ b/guide/english/c/more-math/index.md @@ -42,15 +42,39 @@ Because C is low level as mentioned before, you have access to the individual bi ### AND `c = a & b;` will perform a bitwise AND. This means that if the first bit of `a` and the first bit of `b` are both 1, the first bit of c will be 1, and 0 otherwise. If the second bit of `a` and `b` are both 1, the second bit of c will be 1, and 0 otherwise. This goes on until all bits have been and'd. +Example: + +| Bit | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +|:-----:|---|---|---|---|---|---|---|---| +| a | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | +| b | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | +| a & b | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | + ### OR `c = a | b;` will perform a bitwise OR. The first bit of `c` is 1 if the first bit in either `a` or `b` is 1, the second bit is 1 if the second bit in either `a` or `b` is 1, and so on. +Example: + +| Bit | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +|:------:|---|---|---|---|---|---|---|---| +| a | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | +| b | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | +| a \| b | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | + ### NOT `b = ~a;` will set `b` to the one's complement of `a`, meaning that any 1 becomes a 0 and any 0 becomes a 1. ### XOR `c = a ^ b;` will perform a bitwise XOR. This is an exclusive or, meaning that the first bit of `c` is 1 if either `a` or `b` is 1, but not both. The second bit is 1 if either is 1 but not both, and so on. +Example: + +| Bit | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +|:-----:|---|---|---|---|---|---|---|---| +| a | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | +| b | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | +| a ^ b | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | + ### Shift A bitwise shift will take the bits and move them to some number of places to the left or right. For example, say we have a set of bits: `101110`. C performs an arithmetic shift when bit shifting. Let's use a table to make that more clear: