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.

2
  • 4
    Well, there is a BigInteger class out there... Commented Jun 21, 2016 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. Commented Jun 21, 2016 at 20:33

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

I didnt know it supported any size. Guess I was wrong, Ill check it out! thanks!
@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.
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.
-1

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

2 Comments

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)?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.