How can I apply circular shift on bits in MATLAB?
Show older comments
I want to apply shift right operation on aset of bits
Accepted Answer
More Answers (1)
Walter Roberson
on 11 Apr 2013
MATLAB does not offer that operation directly.
You can extract the bits that would be shifted "off the bottom", do the shift, and then put the bits back on top. Or you can proceed numerically, such as
mod(x,2)*2^7 + floor(x/2)
7 Comments
Sana Shaikh
on 11 Apr 2013
Sana Shaikh
on 13 Apr 2013
sushmitha kemisetti
on 6 Jun 2017
what is the numerical function for circular left shift?
Walter Roberson
on 6 Jun 2017
Edited: Walter Roberson
on 6 Jun 2017
Supposing your array is named YourMatrix, and each of the values is to individually be left-shifted by K bits, then:
vc = class(YourMatrix);
switch vc
case 'int8'; uc = 'uint8'; wl = 8;
case 'uint8'; uc = 'uint8'; wl = 8;
case 'int16'; uc = 'uint16'; wl = 16;
case 'uint16'; uc = 'uint16'; wl = 16;
case 'int32'; uc = 'uint32'; wl = 32;
case 'uint32'; uc = 'uint32'; wl = 32;
case 'int64'; uc = 'uint64'; wl = 64;
case 'single'; uc = 'uint32'; wl = 32;
case 'double'; uc = 'uint64'; wl = 64;
otherwise; error('YourMatrix is not numeric, is class %s', vc);
end
uMatrix = typecast(YourMatrix, uc);
shifted_uMatrix = bitshift(uMatrix, K, uc) + bitshift( uMatrix, K-wl, uc);
shifted_YourMatrix = typecast(shifted_uMatrix, vc);
... As you can probably see, the process would be much simpler if you were to ask about one particular data type.
sushmitha kemisetti
on 6 Jun 2017
If I give a matrix, then how should I get a matrix, where all elements should be circularly left shifted? Is there any numerical function "mod(x,2)*2^7 + floor(x/2)" like this?
Walter Roberson
on 6 Jun 2017
Do you want the individual bits to be left shifted, or do you want the elements to be left shifted relative to the other elements? For example if you had A = uint8([1 2 3 129]) to be circular left shifted by 2, then do you want the result B = uint8([3 129 1 2]) or do you want the result B = uint8([4, 8, 12, 6]) ?
If you want the elements to be left shifted relative to each other, then
B = circshift(A, -K, 2);
If you want the bits to be circular shifted, then use the code I posted above (which I made a couple of corrections to a moment ago.)
If you want the bits to be circular shifted and you want the operation to be expressed mathematically, it is possible. In the above code, replace
shifted_uMatrix = bitshift(uMatrix, K, uc) + bitshift( uMatrix, K-wl, uc);
with
shifted_uMatrix = mod(uMatrix, 2^(wl-K)) * 2^K + uMatrix ./ 2^(wl-K);
sushmitha kemisetti
on 6 Jun 2017
Thank You!
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!