aspose file tools*
The moose likes Java in General and the fly likes Why no toBinaryString(BigInteger b) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why no toBinaryString(BigInteger b) " Watch "Why no toBinaryString(BigInteger b) " New topic
Author

Why no toBinaryString(BigInteger b)

Varun Chopra
Ranch Hand

Joined: Jul 10, 2008
Posts: 211
I converted a very long binary string to BigInteger using



How can I convert it back to binary string later on? I do not see toBinaryString() method in BigInteger class? I can convert veryLongBinaryString to Long/Integer because string is very very long and I get NumberFormatException on trying to convert to Long/Integer.


-Varun -
(My Blog) - Online Certifications - Webner Solutions
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24168
    
  30

Hi Varun,

There is no toBinaryString() method, but there is a bitLength() method that tells you how many bits there are, and a testBit(int) method that tells you the state of each bit. So create a StringBuilder, store bitLength() in a variable "n", then in a for loop check each bit from n-1 to 0 and append the appropriate "1" or "0" to the StringBuilder. Put this little code snippet into a method and keep it in your personal toolbox for future use!


[Jess in Action][AskingGoodQuestions]
Varun Chopra
Ranch Hand

Joined: Jul 10, 2008
Posts: 211
Thanks Ernest. Actually I got a simple solution:



Now the second problem, is there a direct way to convert this binary string to BitSet object?
[ November 07, 2008: Message edited by: Varun Chopra ]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19556
    
  16

Sure. This is a method I wrote just for this:

Similarly, I also have a format method that can return a binary string from a BitSet. I just hate the way BitSet.toString works.


There is an easier way to convert a BigInteger into a BitSet though:

[ November 07, 2008: Message edited by: Rob Prime ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Varun Chopra
Ranch Hand

Joined: Jul 10, 2008
Posts: 211


Thanks Rob! I had written something like you parse method, but this is much better.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24168
    
  30

Originally posted by Varun Chopra:
Thanks Ernest. Actually I got a simple solution:



Very cool, I learned something today! Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why no toBinaryString(BigInteger b)
 
Similar Threads
Max and Min values
Convert Integer to Short
binary to long
Binary conversion
sum of two int arrays