HOW to convert negative integer to bit in Matlab?
16 views (last 30 days)
Show older comments
Is there some function to do the job? thanks in advance
2 Comments
Askic V
on 6 Jan 2023
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
Answers (2)
Askic V
on 6 Jan 2023
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
on 6 Jan 2023
For a few years now, dec2bin can do it directly. For example
dec2bin(-11,8)
7 Comments
Walter Roberson
on 8 Jan 2023
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.
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!