I ported bit-shifting math from C to Julia and thought I would share notes on gotchas.
Simple changes in operators
- Division - The solidus character,
/
, becomes div in Julia,÷
. The/
in Julia is floating-point division, so it will promote integers to reals. - Exclusive or - The caret character,
^
, becomes the xor symbol,⊻
. The^
in Julia is exponentiation.
Both of these operators are will compile fine but have different meaning, so they are easy to mis-type and not notice.
For-loops change scope and increment
In C, the variable j
exists after the loop.
for (j = 1; j < DIM; j++)
if ((P >> j & 1) == (P & 1))
continue;
else
break;
if (j != DIM)
J -= j;
In Julia, for-loops have a new scope for the loop variable.
j = -1
for j = 1:3
println(j)
end
println(j)
This will print 1, 2, 3, -1. We can rewrite the for-loop as a while-loop, which is generally handy when C for-loops do lots of initialization and increments.
j = 1
while j < DIM
if ((P >> j & one(P)) == (P & one(P)))
j += 1
else
break
end
if j != DIM
J -= j
end
Operator precedence changes
C and Julia group mathematical operations differently. They put implicit parentheses in different places. For instance, this small expression means something different in both languages.
temp2 = S << DIM - xJ % DIM;
The operator precedence in C is 1. %
, 2. -
, 3. <<
, 4. =
.
In Julia, it’s 1. <<
, 2. %
, 3. -
, 4. =
. We could put in all of the parentheses, or just those we need.
temp2 = S << (DIM - xJ % DIM)
Maybe we can look at a few operators, listed from high precedence to low, left-to-right, to pick out differences.
C precedence for select operators.
(* / %) (+ -) (<< >>) (< <= > >=) (== !=) (&) (^) (|) (&&) (||) (= += -= <<= >>= &=)
(<< >>) (* / %) (& ÷) (+ - | ⊻) (> < >= <=) (== !=) (&&) (||) (= += -= &= <<= >>=)
Julia precedence for select operators.
The bit-shifting operators move above addition and subtraction. The XOR and AND operators move above greater-than and less-than. In general, it’s good to double-check the C precedence.
HTH!