How can I convert a negative integer to a binary string, in other words, how can I find Two's Complement in MATLAB?

59 次查看(过去 30 天)
DEC2BIN converts non-negative decimal integers to a binary string. I want to create binary strings, with a leading sign bit, from any (negative or positive) integer.

采纳的回答

MathWorks Support Team
This can be accomplished using the TYPECAST function. For example, to find a binary string for 'n' with respect to 8-bit two's complement, you can use the command,
dec2bin(typecast(int8(n),'uint8'))
  6 个评论
Walter Roberson
Walter Roberson 2020-10-1
You cannot get back the correct number if you convert -5.82 to fewer bits.
value = -5.82;
bits32 = dec2bin(typecast(single(value),'uint32'))
retrieved = typecast(uint32(bin2dec(bits32)),'single');
value - retrieved
ans =
single
1.716614e-07
The best retrieved value you can get differs from the original by about 3 parts per billion.
Walter Roberson
Walter Roberson 2020-10-2
Sure there are other ways to generate 32 bit representations of double precision numbers, but think about this for a moment:
There are at most 2^32 different 32 bit numbers.
In double precision, for any given floating point mantissa, there are 52 bits of fraction, so thare are at least 2^52 different double precision numbers. For example 1 + (0:2^52-1)/2^53 constructs 2^52 different double precision floating point numbers with the same mantissa:
>> num2hex(1)
ans =
'3ff0000000000000'
>> num2hex(2-eps)
ans =
'3fffffffffffffff'
>> log2(eps)
ans =
-52
By the Pigeon Hole principle, it is obvious that you cannot come even close to representing all possible double precision numbers in 32 bits. No matter what encoding you use for the 32 bits, there are at most 2^32 different states, and that is not enough to encode 2^52 different values.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by