HOW to convert negative integer to bit in Matlab?
34 次查看(过去 30 天)
显示 更早的评论
Is there some function to do the job? thanks in advance
2 个评论
Askic V
2023-1-6
Please read this thread:
https://www.mathworks.com/matlabcentral/answers/98649-how-can-i-convert-a-negative-integer-to-a-binary-string-in-other-words-how-can-i-find-two-s-comple
回答(2 个)
Askic V
2023-1-6
Wel, you can use something like this (assuming you're working strictly with integers):
s = -10
b = dec2bin(typecast(int8(s),'uint8'))
s_recovered = typecast(uint8(bin2dec(b)),'int8')
Walter Roberson
2023-1-6
For a few years now, dec2bin can do it directly. For example
dec2bin(-11,8)
7 个评论
Walter Roberson
2023-1-8
So there are very small number of representations used for negative integers, and two of those together cover the great majority of the cases.
But when it comes to binary numbers that include negative fractions then the only common representations are IEEE 754 Binary Single Precision (a 32 bit representation) and IEEE 754 Binary Double Precision (a 64 bit representation.) There are a couple of other special-purpose representations, such as Intel's 80-bit Extended Precision. IBM uses a slightly different representation for its GPUs. There is an IEEE-754 standard for "Half Precision" (a 16 bit representation) which MATLAB implements as half which is not used much outside of Deep Learning.
Other than the Deep Learning "half precision" context, people who want negative binary fractions typically use custom fixed-point formats, typically using separate sign, and a fixed number of bits for before the decimal place, and a fixed number of bits for after the decimal place. Applications in which you need a "small" binary fraction often have very specific dynamic ranges that they need to operate over, for which it does not make sense to use a standardized representation such as "half precision"
Because of this... before we can tell you how to convert negative fractional values to binary, you need to define for us exactly what binary representation you want to use.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!