what is the function of $value & 15 - arrays

I have been going over a perl book i have recently purchased, and while reading I noticed a block of code that confused me..
use integer;
$value = 257;
while($value){
unshift #digits, (0..9,a..f)[$value & 15];
$value /= 16;
}
print digits;
the book mentions the purpose was to reverse the order of digits. however, new to perl I am having trouble figuring out what [$value & 15] is doing.

It's a bitwise and operation.
What it's doing is performing a bitwise and using the value of 15 and whatever value is contained in $value.
The resulting value is the decimal value that corresponds to the result of a bitwise and with the lower 4 bits of the value.
Ex:
$value = 21
which has a binary representation of: 0b10101
Performing a bitwise and with 15 means that any bits in $value will be zeroed if they are either outside the lower 4 bit range, or contain no 1's in the lower 4 bits.
The result is:
0b10101
&
0b 1111
-------
0b00101 = 5
Looking up the truth tables for performing bitwise operations will help with stuff like this in the future, but when performing an AND with any value, the result is only true, when both bits are 1, 0 otherwise.
V1 | V2 | V1 & V2
-----------------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

Related

Using Bitwise Operators in C [duplicate]

This question already has answers here:
How does this work? Weird Towers of Hanoi Solution
(3 answers)
Closed 3 years ago.
I am a beginner to C language.I have a code for towers of hanoi but can someone explain me what are these bitwise operators doing ie if value of i is 1 what will be the source and target output value ?
source = (i & i-1) % 3;
target = ((i | i-1) + 1) % 3;
i & i-1 turns off the lowest set bit in i (if there are any set). For example, consider i=200:
200 in binary is 1100 1000. (The space is inserted for visual convenience.)
To subtract one, the zeros cause us to “borrow” from the next position until we reach a one, producing 1100 0111. Note that, working from the right, all the zeros became ones, and the first one became a zero.
The & produces the bits that are set in both operands. Since i-1 changed all the bits up to the first one, those bits are clear in the &—none of the changed bits are the same in both i and i-1, so none of them is a one in both. The other ones in i, above the lowest one bit, are the same in both i and i-1, so they remain ones in i & i-1. The result of i & i-1 is 1100 0000.
1100 0000 is 1100 1000 with the lowest set bit turned off.
Then the % 3 is selecting which pole in Towers of Hanoi to use as the source. This is discussed in this question.
Similarly i | i-1 turns on all the low zeros in i, all the zeros up to the lowest one bit. Then (i | i-1) + 1 adds one to that. The result is the same as adding one to the lowest one bit in i. That is, the result is i + x, where x is the lowest bit set in i. Using our example value:
i is 1100 1000 and i-1 is 1100 0111.
i | i-1 is 1100 1111.
(i | i-1) + 1 is 1101 0000, which equals 1100 1000 + 0000 1000.
And again, the % 3 selects a pole.
A quick overview of bitwise operators:
Each operator takes the bits of both numbers and applies the operation to each bit of it.
& Bitwise AND
True only if both bits are true.
Truth table:
A | B | A & B
-------------
0 | 0 | 0
1 | 0 | 0
0 | 1 | 0
1 | 1 | 1
| Bitwise OR
True if either bit is true.
Truth table:
A | B | A | B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 1
^ Bitwise XOR
True if only one bit is true.
Truth table:
A | B | A ^ B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0
~ Bitwise NOT
Inverts each bit. 1 -> 0, 0 -> 1. This is a unary operator.
Truth table:
A | ~A
------
0 | 1
1 | 0
In your case, if i = 1,
the expressions would be evaluated as:
source = (1 & 1-1) % 3;
target = ((1 | 1-1) + 1) % 3;
// =>
source = (1 & 0) % 3;
target = ((1 | 0) + 1) % 3;
// =>
source = 0 % 3;
target = (1 + 1) % 3;
// =>
source = 0;
target = 2 % 3;
// =>
source = 0;
target = 2;
Good answer above, here is a high-level approach:
i == 1:
source: (1 & 0). Are both of these values true or >= 1? No they are not. So the overall result is 0, 0 % 3 = 0.
target: ((1 | 0) + 1) % 3.
(1 | 0) evaluates to 1(true) since one of the two values on the sides of the | operator are 1, so now we have (1 + 1). so then it follows we have 2 % 3 = 2.
Source: 0, target: 2

Why must I use the ~ operator when clearing a bit? [duplicate]

This question already has answers here:
How do I set, clear, and toggle a single bit?
(27 answers)
Closed 5 years ago.
For example, if I want to set a bit in y at position n (in C)
y = y | (1 << n)
But if I want to delete a bit in y at position n I have to use the ~ operator after binary AND.
y = y & ~(1 << n);
My question: Why Must I use the ~ operator?
Is this because the result turns into negative area?
If you want to set a bit at third place from the right :
Y : 01001000
1 << 2 : 00000100
Y | (1 << 2) : 01001100 The | is OR, bits are set to 1 if any is 1.
If you want to remove the bit :
1 << 2 : 00000100
~(1 << 2) : 11111011 The ~ is NOT, bits are inversed
Y : 01001100
Y & ~(1 << 2) : 01001000 The & is AND, bits are set to 1 if both are 1.
I suggest you read more about Bitwise operators
No, ~ has nothing to do with interpreting the number as negative: tilde ~ operator interprets the number as a pattern of bits, which it then inverts (i.e. replaces zeros with ones and ones with zeros). In fact, if you apply ~ to an unsigned value, the result would remain positive.
Recall that 1 << k expression produces a pattern of all zeros and a single 1 at the position designated by k. This is a bit mask that can be used to force bit at position k to 1 by applying OR operation.
Now consider what happens when you apply ~ to it: all 0s would become 1s, and the only 1 would become zero. Hence, the result is a bit mask suitable for forcing a single bit to zero by applying AND operation.
The ~ operator turns all of the 0's to 1's and all of the 1's to 0's. In order to clear the bint in position n you want to and it will all ones and a zero in the nth position so shift a one to the nth position and ~ invert all the bits.
1 << n for n==3 (just an example) gives you a pattern 0000000...0001000. ~ negates the bit
pattern to 11111111....11110111. Using the bitwise AND operator (&) will
only set the required bit to 0, all other remain with the same value. It's using
the fact that for a bit b: b & 1 == b.
~ flips all bits, it has nothing to do with negative numbers.
A graphical representation for a sequence of k-bits
pos k-1 k-2 0
+---+---+-------------------+---+---+
1: | 0 | 0 | ··· | 0 | 1 |
+---+---+-------------------+---+---+
pos k-1 k-2 n n-1 0
+---+---+-----+---+---+---+-----+---+
1<<n | 0 | 0 | ··· | 1 | 0 | 0 | ··· | 0 |
+---+---+-----+---+---+---+-----+---+
pos k-1 k-2 n n-1 0
+---+---+-----+---+---+---+-----+---+
~(1<<n) | 1 | 1 | ··· | 0 | 1 | 1 | ··· | 1 |
+---+---+-----+---+---+---+-----+---+

C Programming - XOR Bitwise Operation

What operation does the following ‘C’ statement perform?
star = star ^ 0b00100100;
(A) Toggles bits 2 and 5 of the variable star.
(B) Clears all bits except bits 2 and 5 of the variable star.
(C) Sets all bits except bits 2 and 5 of the variable star.
(D) Multiplies value in the variable star with 0b00100100.
I'm still clueless about this. Can someone help me out?
XOR operator (also called "logical addition") is defined like this:
a b a^b
-----------
0 0 0
0 1 1
1 0 1
1 1 0
So a^0 leaves a intact while a^1 toggles it.
For multiple-bit values, the operation is performed bitwise, i.e. between corresponding bits of the operands.
If you know how XOR works, and you know that ^ is XOR in C, then this should be pretty simple. You should know that XOR will flip bits where 1 is set, bits 2 and 5 of 0b00100100 are set, therefore it will flip those bits.
From an "during the test" standpoint, let's say you need to prove this to yourself, you really don't need to know the initial value of star to answer the question, If you know how ^ works then just throw anything in there:
00100100
^10101010 (star's made up value)
---------
10001110 (star's new value)
bit position: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0
|---|---|---|---|---|---|---|---
star's new v: | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0
|---|---|---|---|---|---|---|---
star's old v: | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0
Then check your answers again, did it:
(A) Toggles bits 2 and 5 of the variable star. (Yes)
(B) Clears all bits except bits 2 and 5 of the variable star. (Nope)
(C) Sets all bits except bits 2 and 5 of the variable star. (Nope)
(D) Multiplies value in the variable star with 0b00100100. (36x170 = 142? Nope)
It is (A) toggles bits 2 and 5.
The following is the truth table for the XOR operation:
x y x^y
0 0 0
1 0 1
0 1 1
1 1 0
You can see from the table that x XOR 0 = x and x XOR 1 = !x.
XOR is a bitwise operation, so it operates on individual bits. Therefore if you XOR star with some constant, it will toggle the 1 bits in the constant.
You can find some explanation e.g. here.
The exclusive OR has this truth table:
A B A^B
-----------
1 1 0
1 0 1
0 1 1
0 0 0
We can see that if B is true (1) then A is flipped (toggled), and if it's false (0) A is left alone. So the answer is (A).
XOR operator returns 0 if both inputs are same otherwise returns 1 if both inputs are different.For Example the Given Truth Table :-
a=1 b=1 => a^b=0,
a=0 b=0 => a^b=0,
a=0 b=1 => a^b=1,
a=1 b=0 => a^b=1.
well xor is binary operator that work on bits of 2 nos.
rule of xoring:for same bit ans is 0 and for different bit ans is 1
let
a= 1 0 1 0 1 1
b= 0 1 1 0 1 0
--------------
c= 1 1 0 0 0 1
--------------
compare bit of a and b bit by bit
if same put 0 else put 1
xor is basically used to find the unique in given set of duplicate no.
just xor all nos. and u will get the unique one(if only single unique is present)

how does it works "$_ & 1" in perl

I am perl beginner, I am reading upon grep function to filter a list. I came across the following program.
#!/usr/bin/perl
use strict;
use warnings;
# initialize an array
my #array = qw(3 4 5 6 7 8 9);
# first syntax form:
my #subArray = grep { $_ & 1 } #array;
the statement my #subArray = grep { $_ & 1 } #array; returns odd-numbers in #array. I didn't understand how the expression($_ & 1) works. I searched in Google but did not found any useful links.
Is that any kind of special operator ?
Are there any other variants of that EXPR ?
Thanks in Advance.
$_ is the variable holding the currently tested value, & is the binary AND operator, and 1 is just the number one. This expression combines all the bits of both $_ and 1 with each other by logical AND. So it returns 1 if the value is odd and 0 if the value is even.
As an example, lets assume $_ is 123 then it's binary representation would be 1111011. The decimal number 1 would be 00000001, so combining all bits by AND you get
123 = 1111011
1 = 0000001
- AND -
0000001 = 1
Another example 200 & 100
200 = 11001000
100 = 01100100
- AND --
01000000 = 64
As many have pointed out, & is the bitwise-and operator. This means that the two numbers that are compared are turned into bits and compared:
For example, 3 & 1 returns 1, which evaluates to true inside the grep:
Num | Bits
----+-----
3 | 1 1
& 1 | 0 1
----+-----
1 | 0 1 <- result of 'and'ing each bit column
Similarly, 4 & 1 returns 0, which is false:
Num | Bits
----+-------
4 | 1 0 0
& 1 | 0 0 1
----+-------
0 | 0 0 0 <- all zeros because no column contains 1 & 1
That said, An alternative way to filter odd numbers is to mod the number with 2:
my #odd = grep { $_ % 2 } 1 .. 7; # 1, 3, 5, 7
grep{ $_ & 1}
Will go over every element of your array and do a bit-wise match with 1
This means that grep will match any element that has a 1 as last (lsb) bit.
Since only odd numbers have a 1 as lsb this will only return odd numbers
& is the bitwise AND
$_ is the current expression. In this case each array element.
& is the binary AND operator.
So, in short, the grep will match any array element that is an odd number.
The use of $_ with grep is documented in the perldoc.
The meaning of & is also in the perldoc.
$_ is a variable set by the grep function. Most of the perl functions manipulate $_ if not specified otherwise. Grep calls the defined anonymous sub (which is { $_ & 1 }) for each elements of #array and makes a bitwise &. If the result is a true value, then it is added to the resulting array.

Logic Proof of Associative Property for XOR

I came across a common programming interview problem: given a list of unsigned integers, find the one integer which occurs an odd number of times in the list. For example, if given the list:
{2,3,5,2,5,5,3}
the solution would be the integer 5 since it occurs 3 times in the list while the other integers occur even number of times.
My original solution involved setting up a sorted array, then iterating through the array: For each odd element I would add the integer, while for each even element I would subtract; the end sum was the solution as the other integers would cancel out.
However, I discovered that a more efficient solution existed by simply performing an XOR on each element -- you don't even need a sorted array! That is to say:
2^3^5^2^5^5^3 = 5
I recall from a Discrete Structures class I took that the Associate Property is applicable to the XOR operation, and that's why this solution works:
a^a = 0
and:
a^a^a = a
Though I remember that the Associative Property works for XOR, I'm having trouble finding a logical proof for this property specific to XOR (most logic proofs on the Internet seem more focused on the AND and OR operations). Does anyone know why the Associative Property applies to the XOR operation?
I suspect it involves an XOR identity containing AND and/or OR.
The associative property says that (a^b)^c = a^(b^c). Since XOR is bitwise (the bits in the numbers are treated in parallel), we merely need to consider XOR for a single bit. Then the proof can be done by examining all possibilities:
abc (a^b) (a^b)^c (b^c) a^(b^c)
000 0 0 0 0
001 0 1 1 1
010 1 1 1 1
011 1 0 0 0
100 1 1 0 1
101 1 0 1 0
110 0 0 1 0
111 0 1 0 1
Since the third column, (a^b)^c, is identical to the fifth column, a^(b^c), the associative property holds.
As long as a ^ b == ~a & b | a & ~b, you can proove that :
(a ^ b) ^ c = ~((~a & b) | (a & ~b)) & c | ((~a & b) | (a & ~b)) & ~c
and
a ^ (b ^ c) = a & ~((~b & c) | (b & ~c)) | ~a & ((~b & c) | (b & ~c))
Are equals.

Resources