您可以
bytes[]从转换后的字符串中进行重构,这是一种实现方法:
public String fromHex(String hex) throws UnsupportedEncodingException { hex = hex.replaceAll("^(00)+", ""); byte[] bytes = new byte[hex.length() / 2]; for (int i = 0; i < hex.length(); i += 2) { bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return new String(bytes);}
另一种方法是使用
DatatypeConverter,从
javax.xml.bind包:
public String fromHex(String hex) throws UnsupportedEncodingException { hex = hex.replaceAll("^(00)+", ""); byte[] bytes = DatatypeConverter.parseHexBinary(hex); return new String(bytes, "UTF-8");}
单元测试以验证:
@Testpublic void test() throws UnsupportedEncodingException { String[] samples = { "hello", "all your base now belongs to us, welcome our machine overlords" }; for (String sample : samples) { assertEquals(sample, fromHex(toHex(sample))); }}
注:领先剥离
00的
fromHex仅仅是必要的,因为的
"%040x"你的填充
toHex方法。如果您不介意将其替换为简单的
%x,则可以将此行放在
fromHex:
hex = hex.replaceAll("^(00)+", "");
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)