Android---16进制与字节数组
2024-10-19 12:45:51
16进制字符串与字节数组进行转换
package string; import java.util.Arrays; /**
* byte[]与16进制字符串相互转换
*
* @date:2017年4月10日 下午11:04:27
*/
public class BytesHexStrTranslate { private static final char[] HEX_CHAR = {'', '', '', '', '', '',
'', '', '', '', 'a', 'b', 'c', 'd', 'e', 'f'}; /**
* 方法一:
* byte[] to hex string
*
* @param bytes
* @return
*/
public static String bytesToHexFun1(byte[] bytes) {
// 一个byte为8位,可用两个十六进制位标识
char[] buf = new char[bytes.length * ];
int a = ;
int index = ;
for(byte b : bytes) { // 使用除与取余进行转换
if(b < ) {
a = + b;
} else {
a = b;
} buf[index++] = HEX_CHAR[a / ];
buf[index++] = HEX_CHAR[a % ];
} return new String(buf);
} /**
* 方法二:
* byte[] to hex string
*
* @param bytes
* @return
*/
public static String bytesToHexFun2(byte[] bytes) {
char[] buf = new char[bytes.length * ];
int index = ;
for(byte b : bytes) { // 利用位运算进行转换,可以看作方法一的变种
buf[index++] = HEX_CHAR[b >>> & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
} return new String(buf);
} /**
* 方法三:
* byte[] to hex string
*
* @param bytes
* @return
*/
public static String bytesToHexFun3(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * );
for(byte b : bytes) { // 使用String的format方法进行转换
buf.append(String.format("%02x", new Integer(b & 0xff)));
} return buf.toString();
} /**
* 将16进制字符串转换为byte[]
*
* @param str
* @return
*/
public static byte[] toBytes(String str) {
if(str == null || str.trim().equals("")) {
return new byte[];
} byte[] bytes = new byte[str.length() / ];
for(int i = ; i < str.length() / ; i++) {
String subStr = str.substring(i * , i * + );
bytes[i] = (byte) Integer.parseInt(subStr, );
} return bytes;
} public static void main(String[] args) throws Exception {
byte[] bytes = "测试".getBytes("utf-8");
System.out.println("字节数组为:" + Arrays.toString(bytes));
System.out.println("方法一:" + bytesToHexFun1(bytes));
System.out.println("方法二:" + bytesToHexFun2(bytes));
System.out.println("方法三:" + bytesToHexFun3(bytes)); System.out.println("=================================="); String str = "e6b58be8af95";
System.out.println("转换后的字节数组:" + Arrays.toString(toBytes(str)));
System.out.println(new String(toBytes(str), "utf-8"));
} }
最新文章
- iOS多线程同步锁
- linux ssh服务器
- 20145215实验五 Java网络编程及安全
- CodeForces - 404A(模拟题)
- vs 折叠跟展开所有方法。
- gitlab的使用
- posix thread API列表
- Mac、Linux与Windows
- HDU 5729 Rigid Frameworks(连通性DP)
- mysql 本机root密码忘记
- 在spring拦截器中response输出html标签到页面
- Saltstack基础
- XML文档操作之JAXP下实现
- iOS监听模式系列之iOS开发证书、秘钥
- IP通信基础学习第六周(上)
- mysql学习记录
- [vscode] pylint在虚拟环境下错误告警问题
- ELK之elasticsearch导致CPU居高不下系统慢解决办法
- Python自学:第二章 动手试一试
- PS设计漂亮网站主页图片的实例教程
热门文章
- 【原】Coursera—Andrew Ng机器学习—课程笔记 Lecture 8_Neural Networks Representation 神经网络的表述
- Write your first jQuery plugin
- Perl 变量:标量变量、数组变量、哈希变量和变量上下文
- UnityGUI Keynote
- SpringSecurity3.X权限原理(转)
- java Web JSTL介绍及基本应用
- Luogu 3537 [POI2012]SZA-Cloakroom
- Browsersync 简介 and 使用
- Servlet请求转发 RequestDispatcher接口.RP
- 循环删除DataTable.Row中的多行问题