0

I am trying to write a method that will convert a String containing only decimal digits to a binary array.

The basic issue is that I cannot use the Integer.parseInt method to treat the string as a an integer. For instance...

Integer.toBinaryString(Integer.parseInt(message));

This will not work for me because the int data type only allows for 4 bytes.

My method must work for a message of any length.

I think some parsing is in order, but I am not sure how to approach this.

rkosegi
  • 14,165
  • 5
  • 50
  • 83
  • 4
    Well, there *is* a `BigInteger` class out there... – Makoto Jun 21 '16 at 20:30
  • I thought about that, but the issue is the same. If the message is 40 characters long, it will be far too big for even BigInteger. I am guessing there is no neat data type that will solve this for me. So I am more looking for a straight forward parsing technique. – Jacob Levinson Jun 21 '16 at 20:33

2 Answers2

4

The BigInteger class can do that for you. It supports any size of integer, and has methods to do all the conversions you want. Just use the constructor which takes a String, and then use toByteArray() to convert it.

byte[] result = (new BigInteger(numberString)).toByteArray();
resueman
  • 10,572
  • 10
  • 31
  • 45
  • I didnt know it supported any size. Guess I was wrong, Ill check it out! thanks! – Jacob Levinson Jun 21 '16 at 20:35
  • @JacobLevinson Yep, it can pretty much handle any size you throw at it without any issue. Plus, it comes with a decent selection of methods to manipulate the data however you want. – resueman Jun 21 '16 at 20:42
  • It worked. Thanks again. It is an interesting project I'm doing in my free time. In my days in grad school I developed an encryption algorithm able to handle any size of key. My plan is to implement this as a simple app. Haven't used Java in years, and I've never done any app coding, so this should be an interesting challenge. – Jacob Levinson Jun 21 '16 at 22:07
-1

You could try approaching it one chunk at a time and concatenating the result. See here how to split the String

Community
  • 1
  • 1
C.Sheahan
  • 1
  • 1
  • 1
    It's unclear to me how one would go about concatenating the integer together. How do you store the size of the integer you would have to glue together (supposing that the string length exceeded 10^308)? – Makoto Jun 21 '16 at 20:38
  • Hes trying to make a binary array just add the next chunk to the next index position. Concatenating may be a poor word but I think its close. – C.Sheahan Jun 21 '16 at 21:20