如何将数字(作为字符串)转换为Java中的字节数组?

时间:2012-11-02 22:43:05

标签: java arrays string bytearray converter

我正在为我正在处理的java项目创建一个特定于方法的方法。 给定的UML指定接受参数static byte[]

的返回类型为(String, byte)

到目前为止,看起来像这样:

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

}

此方法应该将数字(作为String)转换为字节数组。排序必须从最高位到最低位。例如,如果 number String为“732”,则数组的索引0应包含7 最后一个参数(numDigits)应该匹配的长度 字符串传入。

我该怎么做?

3 个答案:

答案 0 :(得分:3)

可以使用charAt()检索字符串中的每个字符。可以通过减去例如:

将char转换为其数字值
char c = number.charAt(0);
byte b = c - '0';

答案 1 :(得分:0)

我不会使用第二个参数,并执行以下操作:

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

答案 2 :(得分:0)

我不明白为什么我们在这里需要这么复杂的代码。

使用JDK附带的方法有什么问题

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

如果排序不符合您的意思,请删除该行。

相关问题