FIX2DEC fails for negative binary string
显示 更早的评论
Dear Sir/Madam,
When fix2dec('10011.10110') is used with negative binary strings the following error occurs.
Any help fixing would be much appreciated.
Error using bitcmp
ASSUMEDTYPE must be an integer type name.
Error in twos2dec (line 47)
x(xneg) = -( bitcmp(x(xneg), nbits(xneg)) + 1 );
Error in fix2dec (line 56)
x = twos2dec(t) .* 2.^-frac;
Regards Joe
回答(4 个)
Walter Roberson
2018-3-22
0 个投票
Negative binary strings do not exist. To represent negative in binary, you have to use an encoding scheme. The three common encoding schemes are
- separated sign, where a bit is reserved for saying whether the value is positive of negative. IEEE 754 format uses separated sign
- one's complement, where each bit of the number is directly inverted. This is not common in practice but it is used in some contexts
- two's complement, in which you invert the bits and then add one. This is common for integer representation.
For one's complement and two's complement if you are using a fixed-point representation with a separator between integer and fraction, then you need to decide whether the fraction is also complemented or not (calculations work out easier if it is complemented.)
Joe Miller
2018-3-22
0 个投票
1 个评论
Walter Roberson
2018-3-22
There is no fix; the function is not broken. You are passing it invalid input.
It would be legitimate to ask for an enhancement to process encodings of negative values, but first you need to define exactly what the desired new encoding is.
Joe Miller
2018-3-22
编辑:Walter Roberson
2018-3-22
1 个评论
Walter Roberson
2018-3-22
The bitcmp() functionality used was valid only until R2014a, and was removed in R2014b. There is no replacement MATLAB call for it.
The n bit two's complement for a value is 2^n-1 minus the value.
Joe Miller
2018-3-23
0 个投票
2 个评论
Walter Roberson
2018-3-23
Please do not create a new Answer for each response. Just click on the "Comment on this Answer" link.
Walter Roberson
2018-3-23
The two's complement for an integer, V, that is n bits long is ((2^n-1)-V) . There is no MATLAB call for this except in the cases where n is 8 or 16 or 32 or 64.
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!