代码之家  ›  专栏  ›  技术社区  ›  EAK TEAM

如何将作为字符串的数值数组转换为字节数组?

  •  -5
  • EAK TEAM  · 技术社区  · 6 年前

    如何存储例如此字符串数组:

    { "128", "128", "127" }
    

    到此字节[]数组:

    [128, 128, 127]
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Oleg Cherednik    6 年前

    确实使用 Byte.parseByte(String) 这样做:

    public static byte[] toByteArray(String[] arr) {
        byte[] res = new byte[arr.length];
    
        for (int i = 0; i < arr.length; i++)
            res[i] = Byte.parseByte(arr[i]);
    
        return res;
    }
    

    附笔。 Java 字节值是 〔128;128〕 . 因此 "128" 将投掷 java.lang.NumberFormatException: Value out of range. Value:"128" Radix:10 . 必须决定要对这些值执行什么操作:抛出异常,因为使用数据无效;或者将其转换为最接近的字节值,如 "128" -> 127 ;甚至忽略这些价值观。这段代码可能是这样的:

    public static byte[] toByteArray(String[] arr) {
        byte[] res = new byte[arr.length];
    
        for (int i = 0; i < arr.length; i++) {
            try {
                res[i] = Byte.parseByte(arr[i]);    
            } catch(Exception e) {
                res[i] = // TODO action for incorrect value
            }
        }
    
        return res;
    }