Matlab: Convert a signed binary vector into signed integer

Status
Not open for further replies.

neoflash

Advanced Member level 1
Joined
Jul 2, 2005
Messages
492
Helped
10
Reputation
20
Reaction score
2
Trophy points
1,298
Activity points
4,759
For example, "101" is a negative binary variable. How to convert it into decimal in matlab?
 

Re: Matlab: Convert a signed binary vector into signed integ

Not very straightforward:
Code:
b='101';
if(b(1)==0)
  d=bin2dec(b(2:3));
else
  d=bin2dec(b(2:3))-3;
end
basically, if the MSB is 1 you have a negative number (2's complement in the example).
 
A somewhat old post, but shouldn't it be something like

Code:
    function [y] = sbin2dec(x)
        if(x(1)==0)
            y = bin2dec(x(2:end));
        else
            y = bin2dec(x(2:end)) - 2 ^ (length(x) - 1);
    end
 
There is a typo in the code, it should be:

if (x(1)=='0') % instead of ==0

A somewhat old post, but shouldn't it be something like

Code:
    function [y] = sbin2dec(x)
        if(x(1)==0)
            y = bin2dec(x(2:end));
        else
            y = bin2dec(x(2:end)) - 2 ^ (length(x) - 1);
    end
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…