Clear Filters
Clear Filters

HOW to convert negative integer to bit in Matlab?

16 views (last 30 days)
Is there some function to do the job? thanks in advance
  2 Comments
Zoran
Zoran on 6 Jan 2023
and is there some function that can help me convert decimal numbers into bits?
Askic V
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

Sign in to comment.

Answers (2)

Askic V
Askic V on 6 Jan 2023
Wel, you can use something like this (assuming you're working strictly with integers):
s = -10
s = -10
b = dec2bin(typecast(int8(s),'uint8'))
b = '11110110'
s_recovered = typecast(uint8(bin2dec(b)),'int8')
s_recovered = int8 -10

Walter Roberson
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
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.

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!