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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by