user1795595
user1795595

Reputation: 19

How do I convert a number (as a String) to an array of bytes in Java?

I'm creating a method specific method for a java project i'm working on. The UML given specifies the return type to be of static byte[] that accepts the arguments (String, byte)

So far, looks like this:

public static byte[] convertNumToDigitArray(String number, byte numDigits) {

}

This method is supposed to convert a number (as a String) to an array of bytes. The ordering must go from most to least significant digits. For example, if the number String is “732” then index 0 of the array should contain 7.
The last argument (numDigits) should match the length of the string passed in.

How do I do this?

Upvotes: 1

Views: 313

Answers (3)

ThePerson
ThePerson

Reputation: 3236

I don't see why we need such complex code here.

What's wrong with just using the methods that come with the JDK

public static byte[] convertNumToDigitArray(String number, byte numDigits) {
    byte[] bytes = number.getBytes();
    Arrays.sort(bytes);
    return bytes;
}

If the sorting isn't what you meant, just remove that line.

Upvotes: 0

jlordo
jlordo

Reputation: 37813

I would not use the 2nd parameter and do something like this:

public static byte[] convertNumToDigitArray(String number) {
    if (number != null && number.matches("\\d*") {
        byte[] result = new byte[number.length()];
        for (int i = 0; i < number.length(); i++) {
            result[i] = Byte.parseByte("" + number.charAt(i));
        }
        return result;
    } else {
        throw new IllegalArgumentException("Input must be numeric only");
    }
}

Upvotes: 0

Tyler Durden
Tyler Durden

Reputation: 11532

Each character in the string can be retrieved using charAt(). The char can be converted to its digit value by subtracting, eg:

char c = number.charAt(0);
byte b = c - '0';

Upvotes: 3

Related Questions