繁体   English   中英

将空格分隔的字符串值(由整数组成)存储到java中的字节数组中

[英]Storing string value (consisting of integers) seperatated by space into byte array in java

我正在编写一个Java程序,该程序需要将字符串的值存储到字节数组中(整数值在字符串中用空格分隔)。 谁能帮我解决这个问题。

例如:

输入:String str =“ 71 17 -93 -104”;

要求的输出:

// Byte array variable, byte[] myByte

myByte[0] = 71,

myByte[1] = 17,

myByte[2] = -93,

myByte[3] = -104

但是,我已经将字符串值存储在整数数组中,但是我感到很难将其存储在字节数组中。 我曾用于在整数数组中存储字符串值的代码:

       `String numbers = "71 17 -93 -104";
        String[] nums = numbers.split(" ");
        for(int i=0; i< nums.length; i++)
        {
            System.out.println(nums[i]); 
        }
        int StrArrLen = nums.length;
        int[] myArray = new int[StrArrLen];
        for(int i=0; i< StrArrLen; i++)
        {
            myArray[i] = Integer.parseInt(nums[i]); 
        }
        System.out.println("\nResult:");
        for(int i=0; i< StrArrLen; i++)
        {
            System.out.println(myArray[i]); 
        }`

问候

像这样将整数类型转换为字节。 您必须确保整数在-128到127之间。

String numbers = "71 17 -93 -104";
    String[] nums = numbers.split(" ");
    for(int i=0; i< nums.length; i++)
    {
        System.out.println(nums[i]); 
    }
    int StrArrLen = nums.length;
    byte[] myArray = new byte[StrArrLen];
    for(int i=0; i< StrArrLen; i++)
    {
        myArray[i] = (byte)Integer.parseInt(nums[i]);

    }
    System.out.println("\nResult:");
    for(int i=0; i< StrArrLen; i++)
    {
        System.out.println(myArray[i]); 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM