how to do left and right bit rotation
Ältere Kommentare anzeigen
Hi. I am trying to convert a matrix into 8 bit binary and then want to apply different bit rotations in different rows.e.g for row 1, 2bits will be rotated right and for row 2, 3 bits right rotation.
M=[2 32 45;3 54 12 98;134 245 69];
m1=(str2num(dec2bin(M)));
m=reshape(m1,[3 3]);
mm=m(:);
disp(dec2bin(bit_rotate(m,1),8))% error in this line.
%bitrotation function
function data = bit_rotate(data,nBits)
dataBits = log2(double(intmax(class(data)))+1); %# Number of bits in data
nBits = rem(nBits,dataBits); %# No need to rotate by dataBits bits or more
if nBits == 0 %# No bit rotation needed, just return
return
end
shiftedData = bitshift(data,nBits); %# Bit shift the data
lostData = bitxor(data,bitshift(shiftedData,-nBits)); %# Find the lost bits
rotatedData = bitshift(lostData,nBits-sign(nBits)*dataBits); %# Rotate them
data = shiftedData+rotatedData; %# Add the rotated bits to the shifted bits
end
6 Kommentare
Walter Roberson
am 5 Sep. 2019
The most efficient way is to use a pre-calculated lookup table.
For left rotation by 1 bit, if the value is < 128 then multiply it by 2. If it is >= 128 then subtract 128, multiply by 2, and add 1.
sadiqa ilyas
am 5 Sep. 2019
Walter Roberson
am 5 Sep. 2019
function result = rotate_left_n(value, n)
result = value;
for K = 1 : n
result = rotate_left_1(result);
end
end
sadiqa ilyas
am 5 Sep. 2019
Walter Roberson
am 5 Sep. 2019
It is probably waiting for you to define a function rotate_left_1 according to the algorithm I suggested
sadiqa ilyas
am 6 Sep. 2019
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Geometric Geodesy finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!