How to convert BigInteger into binary?

10 ビュー (過去 30 日間)
Ammy
Ammy 2022 年 3 月 12 日
編集済み: John D'Errico 2022 年 3 月 12 日
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'

採用された回答

John D'Errico
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)
B = '10011100000010011000000011110110100110100000111111110111001000110111011110100110000110110011011101000110'
Is that correct?
C = dec2bin(sym('12362534624362643243256346523462'))
C = '10011100000010011000000011110110100110100000111111110111001000110111011110100110000110110011011101000110'
isequal(B,C)
ans = logical
1
  1 件のコメント
Ammy
Ammy 2022 年 3 月 12 日
@John D'Errico Thank you very much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by