字节数组byte[]与16进制字符串的相互转化
很多时候我们需要将字节数组转化为16进制字符串来保存,尤其在很多加密的场景中,例如保存密钥等。
下面使用BigInteger提供一个非常简单的方案。
package com.zzj.encryption;
import java.math.BigInteger;
public class Bytes2HexTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String s = "我是程序猿!";
byte[] bs = s.getBytes("UTF-8");
/**
* 第一个参数要设置为1
* signum of the number (-1 for negative, 0 for zero, 1 for positive).
*/
BigInteger bi = new BigInteger(1, bs);
String hex = bi.toString(16);
System.out.println(hex);
// 还原
bi = new BigInteger(hex, 16);
bs = bi.toByteArray();// 该数组包含此 BigInteger 的二进制补码表示形式。
byte[] tempBs = new byte[bs.length - 1];
byte[] originBs = bs;
if (bs[0] == 0) {
System.out.println("去补码...");
System.arraycopy(bs, 1, tempBs, 0, tempBs.length); // 去掉补码
originBs = tempBs;
}
s = new String(originBs, "UTF-8");
System.out.println(s);
}
}
测试结果:e68891e698afe7a88be5ba8fe78cbfefbc81 去补码... 我是程序猿!修改源数据:
String s = "123456";测试结果:
313233343536 123456没有去补码了!
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇: El表达式运算符
