gpt4 book ai didi

java - 将十六进制字符串转换为字节

转载 作者:行者123 更新时间:2023-11-29 05:41:46 28 4
gpt4 key购买 nike

我有一个值为 0xE20x800x93 的字符串。我尝试像这样转换它们并且有效

byte[] bs = new byte[]{
(byte) 0xE2,(byte) 0x80, (byte) 0x93
};

但我想要的是不进行显式转换,我需要将其转换为字节数组。

或者至少是一种转换为 byte 对象而不是 byte[] 对象的方法。

最佳答案

你可以在一行(虽然很长)中完成:

byte[] bytes = Arrays.copyOfRange(new ByteBuffer().putInt(Integer.parseInt(str.replace("0x", ""), 16)).array(), 1, 4);

这假设您刚好有 3 个字节要获取。如果是可变长度,下面的代码更通用,但稍微冗长一些,因为它使用输入的长度来确定最终结果的大小:

byte[] bytes = Arrays.copyOfRange(new ByteBuffer().putInt(Integer.parseInt(str.replace("0x", ""), 16)).array(), 4 - str.length() / 4, 4);

关于java - 将十六进制字符串转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266469/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com