Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why no toBinaryString(BigInteger b)

 
Varun Chopra
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Varun Chopra
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Varun Chopra
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Thanks Rob! I had written something like you parse method, but this is much better.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Varun Chopra:
Thanks Ernest. Actually I got a simple solution:



Very cool, I learned something today! Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic