Find out number of bits needed to represent a positive integer in binary?

조회 수: 10 (최근 30일)
How to compute the bit length of a positive integer-the number of bits to represent a positive integer. For example, we have:
integer bits
0 1
1 1
2 2
3 2
4 3
5 3
6 3
7 3
8 4
9 4
How to compute the bit length of an arbitrary large integer?

채택된 답변

Guillaume
Guillaume 2017년 8월 16일
편집: Guillaume 2017년 8월 16일
trivially with log2 (and ceil).
I have no idea what from the cryptographic perspective mean. It's the same from any perspective. It's just basic maths.

추가 답변 (3개)

Bruno Luong
Bruno Luong 2021년 1월 9일
>> I=0:9
I =
0 1 2 3 4 5 6 7 8 9
>> n=nextpow2(I+1)
n =
0 1 2 2 3 3 3 3 4 4

Tamamo Nook
Tamamo Nook 2021년 1월 9일
Try this
integer=5; % Integer that you wanna calculate the binary bits
bits=log2(integer);
if integer==0;
bits=1
elseif bits==floor(bits);
bits=bits+1
else
bits=ceil(bits)
end%if

Walter Roberson
Walter Roberson 2021년 1월 9일
ceil(log2(X+1))
Does not work for 0, but 0 is not a positive integer.
  댓글 수: 1
Bruno Luong
Bruno Luong 2021년 1월 9일
편집: Bruno Luong 2021년 1월 9일
I would argue it is still correct. You need no more than 0 bit to store 0. After all the bits are implicit to be 0s beyong the explcit interval.
>> polyval([],2) % 0 byte
ans =
0
>> polyval([1],2)
ans =
1
>> polyval([1 0],2)
ans =
2
>> polyval([1 1],2)
ans =
3
>>

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by