Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 必须将整数转换为二进制_Matlab - Fatal编程技术网

Matlab 必须将整数转换为二进制

Matlab 必须将整数转换为二进制,matlab,Matlab,我正在编写一个用户定义的函数来将整数转换成二进制。可以使用该函数转换的最大数字应该是带 16 1 s。如果输入的数字较大,则函数应显示错误 消息在我的代码中,我试图根据余数将数字0或1添加到向量x中,然后我想反转我的最终向量,以二进制形式显示一个数字。以下是我所拥有的: function [b] = bina(d) % Bina is a function that converts integers to binary x = []; y = 2; in = d/2; if d >

我正在编写一个用户定义的函数来将整数转换成二进制。可以使用该函数转换的最大数字应该是带 16 1 s。如果输入的数字较大,则函数应显示错误 消息在我的代码中,我试图根据余数将数字0或1添加到向量x中,然后我想反转我的最终向量,以二进制形式显示一个数字。以下是我所拥有的:

function [b] = bina(d)
% Bina is a function that converts integers to binary

x  = [];
y  = 2;
in = d/2;

if d >=(2^16 -1)
   fprintf('This number is too big')
else
    while in > 1
        if in >= 1
            r = rem(in,y);
            x = [x r]
        end
    end
end

end

当您坚持循环时:

x = [];
y = 2;
in = d;


if d >=(2^16 -1)
   fprintf('This number is too big')
else
   ii = 1;
   while in > 0
        r = logical(rem(in,y^ii));
        x = [r x];
        in = in - r*2^(ii-1);
        ii = ii+1;
   end
end

b = x;
您的想法是正确的,但是您需要在每次迭代中更新while循环中的变量。这主要是在中的
,您需要减去余数。只需将二进制余数存储在变量
x
中即可

你可以用计算机检查你的结果

x = double( dec2bin(d, 16) ) - 48
您还可以使用for循环,通过使用

find( d < 2.^(1:16),1)
查找(d<2.^(1:16),1)
然后

if d >=(2^16 -1)
   fprintf('This number is too big')
else
   for ii = 1:find( d < 2.^(1:16),1)
        r = logical(rem(in,y^ii));
        x = [r x];
        in = in - r*2^(ii-1)
   end
end
如果d>=(2^16-1)
fprintf('此数字太大')
其他的
对于ii=1:find(d<2.^(1:16),1)
r=逻辑(rem(in,y^ii));
x=[rx];
in=in-r*2^(ii-1)
结束
结束

如何使用
de2bi
:@m.s.这需要很多人可能没有的通信工具箱。这是家庭作业吗?否则,请查看八度音程中的
dec2bin
。如果您没有在while循环中更新
中的变量,则这将是一个无限循环。