[英]convert string with hexa to byte
我有一个值为0xE20x800x93
的字符串。 我尝试像这样转换它们并且它有效
byte[] bs = new byte[]{
(byte) 0xE2,(byte) 0x80, (byte) 0x93
};
但我想要的是没有进行显式转换,我需要将其转换为字节数组。
或者至少是一种转换为字节对象的方式,而不是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);
从javax.xml.bind
包中尝试DatatypeConverter.parseHexBinary(str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.