Matlab dec2bin给出了错误的值
我正在使用Matlab的dec2bin将十进制数转换为二进制字符串。然而,我得到了错误的结果。例如:Matlab dec2bin给出了错误的值,matlab,Matlab,我正在使用Matlab的dec2bin将十进制数转换为二进制字符串。然而,我得到了错误的结果。例如: >> dec2bin(13339262925365424727) ans = 1011100100011110100101001111010011000111111100011011000000000000 我在C++实现和WalfLAMalpha中都检查过,正确的结果是: 1011100100011110100101001111010011000111111100011011
>> dec2bin(13339262925365424727)
ans =
1011100100011110100101001111010011000111111100011011000000000000
我在C++实现和WalfLAMalpha中都检查过,正确的结果是:
1011100100011110100101001111010011000111111100011011001001010111
我使用Matlab的desc2bin有什么问题吗
谢谢
Gil.整数似乎很长,也许你应该试试
de2bi
函数;
您的代码相当于:
x=13339262925365424727;
dec2bin(x)
但是如果你检查x的值,你会发现它超过了双精度。该数字太大,只能存储在64位的双精度存储器中。精度为2^11,检查eps(x)
要处理大量数据,使用符号工具箱中的vpa
是一个不错的选择,是否可用
以下是使用vpa的解决方案:
function l=ldec2bin(x)
if x>2^52
head=floor(x/2^52);
tail=x-head*2^52;
l=[ldec2bin(head),dec2bin(double(tail),52)];
else
l=dec2bin(double(x));
end
end
用法:
>> ldec2bin(vpa('13339262925365424727'))
ans =
1011100100011110100101001111010011000111111100011011001001010111
/更新:
对于符号变量,我遇到了一个更短的dec2bin
实现:
>> sdec2bin=@(x)(feval(symengine,'int2text',x,2))
sdec2bin =
@(x)(feval(symengine,'int2text',x,2))
>> sdec2bin(sym('13339262925365424727'))
ans =
1011100100011110100101001111010011000111111100011011001001010111
假设输入小于
intmax('uint64')
,如示例中所示,下面是一个不需要符号数学工具箱的解决方案。这支持两个输入参数,匹配,是矢量化的,并且应该快得多:
function s=int2bin(d,n)
%INT2BIN Convert nonnegative integer to a binary string
if isempty(d)
s = '';
return;
end
d = d(:);
if ~isinteger(d) || any(d < 0)
error('int2bin:InvalidIntegerInput',...
'First input must be a nonnegative integer class array.');
end
if nargin < 2
n = 1
else
n = round(double(n));
end
m = double(nextpow2(max(d)));
s = [repmat('0',length(d),n-m) rem(bsxfun(@bitshift,d,1-m:0),2)+'0'];
或者这个使用而不是:
以上所有版本都假定
d
是非负变量,例如uint64(133392262925365424727)
,并且n
是非负数值标量。您可以找到功能齐全的int2bin
和bin2int
功能。谢谢您的帮助!这并不能解决问题fliplr(char(de2bi(133392262925365424727)+48))
与dec2bin(133392262925365424727)相同。de2bi
的文档没有提到它,它似乎也是使用双精度实现的,因此对于大于flintmax
的值,可能会返回不准确的输出。感谢您的帮助!谢谢你的帮助
int2bin = @(d,n)char(rem(bsxfun(@bitshift,d(:),1-max(n,double(nextpow2(max(d(:))))):0),2)+'0');
int2bin = @(d,n)char(~~bsxfun(@bitand,d(:),2.^(max(n,nextpow2(max(d(:)))):-1:0))+'0');