简体   繁体   English

将字符串转换为字节数组但保持相同的值

[英]Converting String to Byte Array but keeping the same values

What I'm trying to do is for example, lets say we had a string that looked like this:例如,我想做的是,假设我们有一个看起来像这样的字符串:

String xyz = "1234567890";

How can I convert that String object into an Byte Array so the result byte array looks like:如何将该字符串 object 转换为字节数组,以便结果字节数组如下所示:

[12, 34, 56, 78, 90]; [12、34、56、78、90];

I've tried various ways, from the very rudimentary xyz.getBytes() along with different encodings, which all just give some random values, albeit prob correct, just not what I'm looking for.我尝试了各种方法,从非常基本的 xyz.getBytes() 以及不同的编码,它们都只是给出了一些随机值,尽管可能是正确的,但不是我想要的。 Tried splitting up the string into an array, something like ["12", 34"....] and trying to convert that into a byte array with no luck.尝试将字符串拆分为数组,例如 ["12", 34"....] 并尝试将其转换为字节数组,但没有成功。

Am I not understanding here how strings are getting converted or is there some way of accomplishing this?我在这里不明白字符串是如何转换的,还是有什么方法可以做到这一点? Any tips appreciated.任何提示表示赞赏。 Thanks!谢谢!

public static void main(String[] args) {
        String xyz = "1234567890";
        byte b[] = new byte[xyz.length() / 2];
        for (int i = 0; i < b.length; i++)
            b[i] = Byte.parseByte(xyz.substring(2 * i, 2 * i + 2));

        for (byte x : b) 
            System.out.println(x);
    }

->Use the substring method, notice that xyz.substring(0, 2) gives you the characters at index 0 and 1, not 2. The upper border is exclusive.

->Use parseByte

Do it as follows:执行以下操作:

import java.math.BigInteger;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // For decimal numbers
        String xyz = "1234567890";
        Byte[] arr = Arrays.stream(xyz.split("(?<=\\G..)")).map(Byte::parseByte).collect(Collectors.toList())
                .toArray(new Byte[0]);
        System.out.println(Arrays.toString(arr));

        // For haxadecimal numbers
        byte[] array = new BigInteger("A145BB5689", 16).toByteArray();
        System.out.println(Arrays.toString(array));
    }
}

Output: Output:

[12, 34, 56, 78, 90]
[0, -95, 69, -69, 86, -119]

Note: The regex (?<=\G..) matches an empty string that has the last match ( \G ) followed by two characters ( .. ) before it ( (?<= ) ).注意:正则表达式(?<=\G..)匹配一个空字符串,该字符串具有最后一个匹配项 ( \G ),后跟两个字符 ( .. ) ( (?<= ) )。

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

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