使用uint64将64位数字从二进制转换为十进制 [英] Convert 64 bit numbers from binary to decimal using uint64
问题描述
我想将64位数字从二进制转换为十进制.由于dec2bin
仅支持多达52位,因此我认为我可以滚动自己的函数并使用uint64
来超出此限制:
I want to convert 64 bit numbers from binary to decimal. Since dec2bin
only supports up to 52 bits, I thought I could roll my own function and use uint64
to go beyond this limit:
function [dec] = my_bin2dec(bin)
v = uint64(length(bin)-1:-1:0);
base = uint64(2).^v;
dec = uint64(sum(uint64(base.*(uint64(bin-'0')))));
end
但是,它不能按预期工作:
However, it does not work as expected:
my_bin2dec('111000000000000000000000000000000000001010110101011101000001110')
ans =
8070450532270651392
my_bin2dec('111000000000000000000000000000000000001010110101011101000001111')
ans =
8070450532270651392
这是正确的结果:
(111000000000000000000000000000000000001010110101011101000001110)bin
= (8070450532270651918)dec
(111000000000000000000000000000000000001010110101011101000001111)bin
= (8070450532270651919)dec
我想念什么?似乎仍有一些操作使用52位双精度算术执行,但我不知道是哪个.
What am I missing? It seems like there is some operation still performed using 52bit double arithmetic, but I don't know which one.
我检查了uint64
是否可用的操作,并且似乎我使用的操作(power
,times
,sum
)在那里:
I checked if the operations are available for uint64
and it seems that the ones I use (power
, times
, sum
) are there:
>> methods uint64
Methods for class uint64:
abs bitxor diff isinf mod plus sum
accumarray bsxfun display isnan mpower power times
all ceil eq issorted mrdivide prod transpose
and colon find ldivide mtimes rdivide tril
any conj fix le ne real triu
bitand ctranspose floor linsolve nnz rem uminus
bitcmp cummax full lt nonzeros reshape uplus
bitget cummin ge max not round xor
bitor cumprod gt min nzmax sign
bitset cumsum imag minus or sort
bitshift diag isfinite mldivide permute sortrowsc
推荐答案
您说的没错
似乎仍然使用52位双精度算法执行某些操作.
It seems like there is some operation still performed using 52bit double arithmetic.
问题出在
dec = uint64(sum(uint64(base.*(uint64(bin-'0')))));
操作sum(uint64(base.*(uint64(bin-'0'))))
给出double
结果,该结果只有大约15个有效数字.这就是为什么您的最低位数是错误的.随后的转换为uint64
并没有帮助,因为精度已经丢失.
The operation sum(uint64(base.*(uint64(bin-'0'))))
gives a double
result, which only has about 15 significant digits. That's why your lowest digits are wrong. Subsequent conversion into uint64
doesn't help, because precision has already been lost.
解决方案是将uint64
结果:
The solution is to sum natively in uint64
. This gives a uint64
result with its full precision:
dec = sum(uint64(base.*(uint64(bin-'0'))), 'native');
这篇关于使用uint64将64位数字从二进制转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!