How to convert BigInteger into binary?
6 次查看(过去 30 天)
显示 更早的评论
import java.math.*;
>> a=BigInteger('12362534624362643243256346523462');
>> b=toString(a);
>> dec2bin(b)
Error using dec2bin (line 24)
D must be numeric.
I have tried this
>> dec2bin(str2double(b))
ans = '10011100000010011000000011110110100110100000111111111000000000000000000000000000000000000000000000000000'
but it is not giving right output
The output should be
'10011100000010011000000011110110100110100000111111110111001000110111011110100110000110110011011101000110'
0 个评论
采纳的回答
John D'Errico
2022-3-12
编辑:John D'Errico
2022-3-12
You would not expect dec2bin to do it, when you convert the number oto a double. It will fail above 2^53-1, and that number is surely too large. Well, you SHOULD not expect it to work, if you understand what a double means, and you DID convert it to a double. The clue as to why it failed is of course in the output you did get. The first 50 bits or so were correct, but then you see entirely zeros. That suggests the problem you had was in the conversion to a double, which threw away all those lower order bits, directly into the bit bucket.
However, this should do it:
import java.math.*;
a=BigInteger('12362534624362643243256346523462');
B = reshape(dec2bin(double(toByteArray(a)))',1,[]);
Note that it may have leading zeros on the highest order byte, because the Java number gets returned as a vector of bytes. I suppose you could zap them away.
B = B(find(B == '1',1,'first'):end)
Is that correct?
C = dec2bin(sym('12362534624362643243256346523462'))
isequal(B,C)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!