How does bitshift work?

조회 수: 10 (최근 30일)
Kaavya N
Kaavya N 2021년 5월 4일
댓글: Scott MacKenzie 2021년 5월 5일
bitshift(56,-1)
gives answer 28 in matlab
My understanding of this working is as follows:
the function converts 56 to binary value ie 0101 0110 and does right shift since its -1
so 0010 1011 -> 2b (hexa)
so the answer should be "2b" right?
How does this function work?
  댓글 수: 4
Stephen23
Stephen23 2021년 5월 5일
편집: Stephen23 2021년 5월 5일
"the function converts 56 to binary value ie 0101 0110"
You appear to have mixed up decimal and hexadecimal:
B = '01010110'; % your binary string
D = pow2(numel(B)-1:-1:0)*sscanf(B,'%1d') % decimal
D = 86
D = bin2dec(B) % decimal
D = 86
H = dec2hex(D) % hexadecimal
H = '56'
H = sprintf('%x',D) % hexadecimal
H = '56'
Kaavya N
Kaavya N 2021년 5월 5일
Thank you

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

채택된 답변

Walter Roberson
Walter Roberson 2021년 5월 4일
dec2bin(56,8)
ans = '00111000'
In other words, your difficulty is that 0101 0110 is not the correct representation for 56.
  댓글 수: 3
Walter Roberson
Walter Roberson 2021년 5월 5일
Consider for a moment that 56 decimal can be divided by 2 to get 28, and then divided by 2 again to get 14, and then divided by 2 again to get 7, but that cannot be divided by 2. That is three divisions, so the binary representation must end in three 0's.
Scott MacKenzie
Scott MacKenzie 2021년 5월 5일
It's also worth noting that with each division-by-two the remainder (0 or 1) becomes part of the binary result. The first remainder is the bit on the right (the least-significant bit). Each successive remainder is appended on the left. The following figure might help. It shows the conversion from decimal 26 to the binary equivalent, 11010.

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

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by