Matlab 二进制表示中两个整数的加法
我想实现的代码将添加两个整数的二进制表示 例如:Matlab 二进制表示中两个整数的加法,matlab,vector,binary,sum,integer,Matlab,Vector,Binary,Sum,Integer,我想实现的代码将添加两个整数的二进制表示 例如: a = [1 1 1 0]; 及 因此,我实现了以下算法: function s=add_binary(a,b) m=length(a); s=zeros(m+1,0); n=length(a); c=0; for ii=n:-1:1 d=floor((a(ii)+b(ii)+c)/2); s(ii)=a(ii)+b(ii)+c-2*d; c=d; end s(1)=c;
a = [1 1 1 0];
及
因此,我实现了以下算法:
function s=add_binary(a,b)
m=length(a);
s=zeros(m+1,0);
n=length(a);
c=0;
for ii=n:-1:1
d=floor((a(ii)+b(ii)+c)/2);
s(ii)=a(ii)+b(ii)+c-2*d;
c=d;
end
s(1)=c;
end
但是,它会返回以下结果:
s=add_binary(a,b)
s =
1 0 0 1
在这里,左边应该有一个额外的1
,这样它就会显示:
1 1 0 0 1
我哪里出错了?这是我的解决方案
function s=add_binary(a,b)
m=length(a);
s=zeros(m+1,1);
n=length(a);
c=0;
for ii=n:-1:1
d=floor((a(ii)+b(ii)+c)/2);
s(ii+1)=a(ii)+b(ii)+c-2*d;
c=d;
end
s(1)=c;
s=s';
end
>> s=add_binary(a,b)
s =
1 1 0 0 1
用于将a
和b
转换为字符串,并用于将其转换为十进制。然后添加它们,并使用将总和转换回二进制。用于拆分字符串,最后用于获得所需结果
s=str2double(num2cell(dec2bin(bin2dec(num2str(a))+bin2dec(num2str(b)))))
% Output for given a and b
%---------------------------
% s =
% 1 1 0 0 1
2011年的一个问题中讨论了这个问题。我想再提两个解决方案:
- 如果您有通信系统工具箱,则可以使用
和bi2de
:de2bi
de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb')
- 如果输入中的“数字”数量已知(且合理),一种解决方案是将所有可能的输入组合存储在某个数据结构中,这将有助于快速访问。一个这样的例子是(尽管它可以很容易地用常规数字数组完成)。我将提供一个小示例来说明这个想法(包括一个基准测试):
我的x64 MATLAB R2017a@Win10的结果如下:
因此,这应该让我们知道哪些方法更快(除非我把包装器函数弄得一团糟)。。。Sardar's method: 0.336414 Dev-iL's method: 0.061656 gnovice's method: 0.022031 dato's method: 0.002123 bi2de method: 0.000356
如果总和的计算是其他更昂贵的操作,
方法的优势是显而易见的MapN
>> a = randi([0 1], [1 6])
a =
0 1 0 1 0 1
>> b = randi([0 1], [1 6])
b =
1 1 0 0 0 1
>> s = add_binary(a, b)
s =
1 0 0 0 1 1 0
它不应该是
s=zeros(m+1,1)
是的,我看到了,它是打字错误,但它仍然有一些缺陷str2double(num2cell(dec2bin(bin2dec(num2str(a))+bin2dec(num2str(b);)))
我也解决了它,我把它作为一个答案贴了出来,这两个输入的最大大小(位数)是多少?最大的产量是多少?当我们在输出中需要比在输入中更多的位时(如在您的示例中),我们应该始终添加另一位,还是在某个点“溢出”并保持相同的大小?
Sardar's method: 0.336414
Dev-iL's method: 0.061656
gnovice's method: 0.022031
dato's method: 0.002123
bi2de method: 0.000356
function s = add_binary(a, b)
a = [0 a];
b = [0 b];
c = a&b;
while any(c)
b = xor(a, b);
a = circshift(c, -1);
c = a&b;
end
s = a+b;
end
>> a = randi([0 1], [1 6])
a =
0 1 0 1 0 1
>> b = randi([0 1], [1 6])
b =
1 1 0 0 0 1
>> s = add_binary(a, b)
s =
1 0 0 0 1 1 0