필터 지우기
필터 지우기

how to do left and right bit rotation

조회 수: 4 (최근 30일)
sadiqa ilyas
sadiqa ilyas 2019년 9월 5일
댓글: sadiqa ilyas 2019년 9월 6일
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
Walter Roberson
Walter Roberson 2019년 9월 5일
It is probably waiting for you to define a function rotate_left_1 according to the algorithm I suggested
sadiqa ilyas
sadiqa ilyas 2019년 9월 6일
thanks

댓글을 달려면 로그인하십시오.

채택된 답변

Bruno Luong
Bruno Luong 2019년 9월 5일
편집: Bruno Luong 2019년 9월 5일
% Test example, 166 corresponds to your example of binary '10100110'
M=[2 32 45;
3 54 166;
134 245 69]
rotfun = @(M,r) reshape(str2num(circshift(dec2bin(M,8),-r,2)),size(M))
rotfun(M,0)
rotfun(M,3)
Results:
ans =
10 100000 101101
11 110110 10100110
10000110 11110101 1000101
ans =
10000 1 1101001
11000 10110001 110101
110100 10101111 101010

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by