Find out number of bits needed to represent a positive integer in binary?
18 次查看(过去 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?
0 个评论
采纳的回答
更多回答(3 个)
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
0 个评论
Walter Roberson
2021-1-9
ceil(log2(X+1))
Does not work for 0, but 0 is not a positive integer.
1 个评论
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!