1

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?

1
  • 2
    If the value of numDigits can be inferred from the value of number, why are both required? Commented Nov 2, 2012 at 22:44

3 Answers 3

3

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

1 Comment

Yea this is certainly a nice trick; too many people are tempted to use Integer.parseInt (or something similar) for this.
0

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");
    }
}

Comments

0

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.

1 Comment

Will using the getBytes() method store each digit of 'number' in ascending indexes?

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.