I think you meant:
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(1 << i); // this is 2^i
cout << key << "\n";
}
}
^
is a bitwise operator for XOR so the code was "valid" from the compiler's point of view.
Why it works:
I cannot find a relevant question but "(1 << i)
" was explained somewhere else. 1
is treated as an integer. Then operator<<
on integer is a bitwise left shift (by i
places).
So it makes 000001
and shifts it left, e.g. when i
is 3 it produces 001000
. Effectively producing 2^i
integer.
Of course one could use something more explicit, however std::pow is defined only for floating point types, so one would need to use some conversions.
(1 << i)
also poses some safety concerns. You need to take care of the type of the values you use for shifting (their size), and value you use for shifting, writing (1<<128)
might give some unexpected results. Anyway it is the best way to get 2^i
for most cases IMO.