Following are the bitwise operators
supported by Julia.
Operator
|
Description
|
~
|
Bit wise not
|
&
|
Bit wise and
|
|
|
Bit wise or
|
$
|
Bit wise XOR
|
>>>
|
Zero fill right shift
|
>>
|
Right shift
|
<<
|
Left shift
|
Before discuss about the Bit wise
operators in detail, will discuss about Binary representations of a number
1's
Complement
1's complement simply inverts the bits,
if the bit is set to zero, it sets the bit to 1 and if the bit is set to 1 it
sets the bit to zero.
Ex:
8 in binary = 0 0 0 0 1 0 0 0
1's complement(8) = 1 1 1 1 0 1 1 1
2's
complement
Negative numbers are stored in 2's
complement form. i.e., -8 is 2's complement of 8.
2's complement is sum of (1's complement
of a number + 1)
Ex:
8 in binary = 0 0 0 0 1 0 0 0
1's complement(8) = 1 1 1 1 0 1 1 1
2's complement(8) = (+) 1
-----------------
1 1 1 1 1 0 0 0
----------------
There fore -8 in 2's complement form is
11111000
Bit
wise not (~)
Inversion operator change the bit value
to zero, if it is one and change the bit value to one if it is zero.
Example
a = 7;
a in binary format is 0 0 0 0 0 1 1 1
~(a) in binary format is 1 1 1 1 1 0 0 0
~(a) represents -8 in binary format.
julia> a=7
7
julia> ~a
-8
Bit
wise and(&), or(|), Ex-OR($)
Bit1
|
Bit2
|
&
|
|
|
$
|
0
|
0
|
0
|
0
|
0
|
0
|
1
|
0
|
1
|
1
|
1
|
0
|
0
|
1
|
1
|
1
|
1
|
1
|
1
|
0
|
julia> a&b 8 julia> a|b 9 julia> a$b 1
Explanation
a = 0000 1000
b = 0000 1001
a&b = 0000 1000
a = 0000 1000
b = 0000 1001
a|b = 0000 10001
a = 0000 1000
b = 0000 1001
a^b = 0000 0001
Bit
Wise Left Shift(<<)
Left shift operator shifts all the bits
to one bit left, i.e, it doubles the value.
Syntax:
variable << n
left shift the variable by 'n' number of times.
Variable << n is equals to variable = variable * 2^n
var = 2;
var << 1 = 2 * 2^1 = 4
var << 2 = 2 * 2^2 = 8
var << 9 = 2 * 2^9 = 1024
julia> a=2; julia> a<<1 4 julia> a<<2 8 julia> a<<3 16
Bit
Wise Right Shift(>>)
Right shift operator shifts all the bits
to one bit right, i.e, it half (divide by 2) the value.
Syntax:
variable >> n : Right shift the variable by 'n' number of times.
Variable >> n is equals to
variable = variable / 2^n
var = 128;
var >> 1 = 128 / (2^1) = 64
var >> 2 = 128 / (2^2) = 32
julia> var = 128; julia> var>>1 64 julia> var>>2 32
Bit
Wise unsigned Right Shift(>>>)
Shifts all the bits to one bit right, and make the left most bit to zero.
Shifts all the bits to one bit right, and make the left most bit to zero.
julia> var=-128 -128 julia> var>>>1 9223372036854775744
Explanation
-128 is
represented in binary like “1111111111111111111111111111111111111111111111111111111110000000”
So
(-128>>>1) is like below sequence.
0111111111111111111111111111111111111111111111111111111111000000
julia> bits(9223372036854775744) "0111111111111111111111111111111111111111111111111111111111000000"
No comments:
Post a Comment