Reputation: 39
I want to optimize this Matlab function that performs bit rotate left for uint64 number
function Sh_x = ROL(x, nShift)
i = 1;
while i <= nShift
y=reshape(dec2bin(typecast(swapbytes(x),'uint8'),8).',1,[]);
bit = double(y(1))-48;
x = bitset(x,64,0,'uint64');
Sh_x = uint64(bitshift(x, 1,'uint64'));
Sh_x = Sh_x + uint64(bit)* uint64(2)^0;
x = Sh_x;
i = i + 1;
end
end
Upvotes: 1
Views: 74
Reputation: 60635
bitshift(x, nShift, 'uint64')
shifts the 64-bit integer left by nShift
values, discarding bits that overflow on the left side, and adding zeros on the right side.
This leads to the left component of the expected output. What you're missing is the bits that overflowed on the left.
bitshift(x, nShift-64, 'uint64')
shifts the 64-bit integer right by 64-nShift
values, discarding values that exit on the right and adding zeros to the left. The remaining bits are the ones that exited left in the first left shift. This leads to the right component of the expected output.
Combine the two using bitor
:
Sh_x = bitor(bitshift(x, nShift, 'uint64'), ...
bitshift(x, nShift-64, 'uint64'), ...
'uint64');
Upvotes: 3