6
i=1
aux=3
aux=$(($aux^$i))
echo $aux
#2
Can someone explain me this code?
6
i=1
aux=3
aux=$(($aux^$i))
echo $aux
#2
Can someone explain me this code?
5
^
is the operator "or exclusive" (bitwise XOR). Basically, it takes the binary representation of the numbers involved and applies the following rules, bit by bit:
So by doing 3 ^ 1
, we have:
00000011 <- 3 em binário
00000001 <- 1 em binário
--------
00000010 <- 2 em binário
In the first 6 positions, the bits are all zero, so the result of these positions will be zero. In seventh position, the first bit is 1 and the other is zero, so the result, according to the above rules, is 1. And in eighth position, both are 1, so the result is zero.
The final result is the binary representation of the number 2.
The expression must be between (( ))
, since this is the construction that allows performing arithmetic operations.
The $
is placed in front of the parentheses so that the result of the expression is assigned to the variable (aux=$(($aux^$i))
). But it could also be done so:
#!/bin/bash
i=1
aux=3
((aux = $aux^$i))
echo $aux
See here the code running
I understood, but in the case I still continued with the following question: Given a given array one asks to show the elements that "occur only once". How does this mechanism work by enabling this, since the comparison occurs between two numbers? https://www.hackerrank.com/challenges/lonely-integer/problem
read num read arr aux=0 for i in $arr; do aux=$(($aux $i)) done echo $aux
@Brunosouto I don’t know if this is what you want to know, but it might help (see method 4): https://www.geeksforgeeks.org/find-the-two-repeating-elements-in-a-given-array/
@Brunosouto I actually think this is it (see method 3): https://codepumpkin.com/find-unique-array-element/#Xorapproach
Browser other questions tagged bash shell-script shell
You are not signed in. Login or sign up in order to post.
When typing
$(( ))
you are entering a special "mathematical environment". Possibly the^
is doing the operationXOR
– Jefferson Quesado