-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwos2dec.m
59 lines (54 loc) · 1.54 KB
/
twos2dec.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function x = twos2dec(t)
% TWOS2DEC Convert binary string two's complement to decimal integer.
%
% Usage: X = TWOS2DEC(T)
%
% Converts the two's complement representation as a string given by T to
% decimal integers X. T can be a character array or cell string. Input
% multiple numbers into T along the rows, and the output will be as a
% column vector. Similarly to BIN2DEC, leading spaces in T are sign
% extended (so treated as either 0 or 1 depending on the first non space
% character), and embedded and trailing spaces are removed.
%
% Example:
% >> twos2dec(['010 111'; ' 010111'; '101011 '; ' 10 1'])
%
% ans =
%
% 23
% 23
% -21
% -3
%
% Inputs:
% -T: string two's complement numbers to convert to decimal integers.
%
% Outputs:
% -X: decimal representation of T.
%
% See also: DEC2TWOS, FIX2DEC, DEC2FIX, BIN2DEC, HEX2DEC, BASE2DEC.
narginchk(1, 1);
if iscellstr(t)
t = char(t);
end
% Convert to numbers.
x = bin2dec(t);
% Get the number of bits as the number of 0's and 1's in each row.
nbits = sum(t == '0' | t == '1', 2);
% Case for negative numbers.
xneg = log2(x) >= nbits - 1;
% xneg = bitshift(x, -(nbits - 1)) == 1;
if any(xneg)
str = strtrim(t(xneg, :));
temp = '';
for b = 1:length(str)
if (b == 1)
%ignora aixo
elseif (str(b) == '0')
temp = strcat(temp, '1');
else
temp = strcat(temp, '0');
end
end
x(xneg) = -( bin2dec(temp) + 1 );
end