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

huangapple go评论108阅读模式
英文:

Converting String to Byte Array but keeping the same values

问题

以下是翻译好的内容:

我尝试做的是,例如,假设我们有一个看起来像这样的字符串:

String xyz = "1234567890";

如何将该String对象转换为字节数组,使得结果字节数组如下:

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

我尝试过各种方法,从非常基础的xyz.getBytes()方法以及不同的编码方式,但都只会得到一些随机值,虽然可能是正确的,但不是我要寻找的结果。我尝试将字符串拆分为数组,类似于["12", "34" ....],然后尝试将其转换为字节数组,但没有成功。

我是不是对字符串的转换方式有什么误解,还是有其他方法可以实现这一点?对任何提示表示感谢!谢谢!

英文:

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:

[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. Tried splitting up the string into an array, something like ["12", 34" ....] and trying to convert that into a byte array with no luck.

Am I not understanding here how strings are getting converted or is there some way of accomplishing this? Any tips appreciated. Thanks!

答案1

得分: 0

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

-> 使用substring方法时,请注意xyz.substring(0, 2)会获取索引为0和1的字符,而不是2。上边界是不包含的。

-> 使用parseByte


<details>
<summary>英文:</summary>

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

答案2

得分: 0

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 hexadecimal numbers
        byte[] array = new BigInteger("A145BB5689", 16).toByteArray();
        System.out.println(Arrays.toString(array));
    }
}

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 ((?<= )).

英文:

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 = &quot;1234567890&quot;;
		Byte[] arr = Arrays.stream(xyz.split(&quot;(?&lt;=\\G..)&quot;)).map(Byte::parseByte).collect(Collectors.toList())
				.toArray(new Byte[0]);
		System.out.println(Arrays.toString(arr));

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

Output:

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

Note: The regex (?&lt;=\G..) matches an empty string that has the last match (\G) followed by two characters (..) before it ((?&lt;= )).

huangapple
  • 本文由 发表于 2020年4月10日 03:07:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61128499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定