How to convert BigInteger into binary?

9 visualizzazioni (ultimi 30 giorni)
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'

Risposta accettata

John D'Errico
John D'Errico il 12 Mar 2022
Modificato: John D'Errico il 12 Mar 2022
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

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by