2008-01-04

Published 星期五, 1月 04, 2008 by with 0 comment

[matlab] 十進位整數轉二補數 - MATLAB





MATLAB 有一個內建函數, dec2bin 可以將 十進位的 整數 (負的還不行 XD) 轉成 二進位的字串 表示, 找了找 好像沒有 將整數 (正或負) 轉成 2 補數的二進位表示 函數, 所以就自己寫了一個, 在這邊備份一下:


function IN_TEMP = signed_dec2bin(IN,ROW,SIZE)


BOTTOM = -(2^(SIZE-1));
UP = 2^(SIZE-1) - 1;


IN_TEMP = zeros(ROW,SIZE);


if (sum(IN < BOTTOM) + sum(IN > UP)) > 0
error('out of range');
else
%for i = 1:length(IN)
for i = 1:ROW
if IN(i) >= 0
[f,e] = log2(max(IN(i)));
IN_TEMP(i,:) = (rem(floor(IN(i)*pow2(1-max(SIZE,e):0)),2)+'0');
IN_TEMP(i,:) = (IN_TEMP(i,:) - 48);
else
IN_ABS = abs(IN(i));
[f,e] = log2(max(IN_ABS));
IN_TEMP(i,:) = (rem(floor(IN_ABS*pow2(1-max(SIZE,e):0)),2)+'0');
IN_TEMP(i,:) = (IN_TEMP(i,:) - 49) .^ 2;
j = SIZE;
while j <= SIZE
if IN_TEMP(i,j) == 0
IN_TEMP(i,j) = 1;
j = 2*SIZE; % jump out the while loop
else
IN_TEMP(i,j) = 0;
j = j - 1;
end
end
end
end
end



      edit

0 Comments:

張貼留言