java byte数组与16进制间的相互转换
java byte数组与16进制间的相互转换
CreationTime--2018年6月11日15点34分
Author:Marydon
1.准备工作
import java.util.Arrays; /**
* Byte[]与hex的相互转换
* @explain
* @author Marydon
* @creationTime 2018年6月11日下午2:29:11
* @version 1.0
* @since
* @email marydon20170307@163.com
*/
public class ByteUtils { // 16进制字符
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
2.byte类型数组转化成16进制字符串
方法一
/**
* 方法一:将byte类型数组转化成16进制字符串
* @explain 字符串拼接
* @param bytes
* @return
*/
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
int num;
for (byte b : bytes) {
num = b < 0 ? 256 + b : b;
sb.append(HEX_CHAR[num / 16]).append(HEX_CHAR[num % 16]);
}
return sb.toString();
}
方法二
/**
* 方法二: byte[] to hex string
* @explain 使用数组
* @param bytes
* @return
*/
public static String toHexString2(byte[] bytes) {
// 一个byte为8位,可用两个十六进制位表示
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;
// 使用除与取余进行转换
for (byte b : bytes) {
if (b < 0)
a = 256 + b;
else
a = b; // 偶数位用商表示
buf[index++] = HEX_CHAR[a / 16];
// 奇数位用余数表示
buf[index++] = HEX_CHAR[a % 16];
}
// char[]-->String
return new String(buf);
}
方法三
/**
* 方法三: byte[]-->hexString
* @explain 使用位运算
* @param bytes
* @return
*/
public static String toHexString3(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int index = 0;
// 利用位运算进行转换,可以看作方法二的变型
for (byte b : bytes) {
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
} return new String(buf);
}
方法四
/**
* 方法四:byte[]-->hexString
* @param bytes
* @return
*/
public static String toHexString4(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
// 使用String的format方法进行转换
for (byte b : bytes) {
sb.append(String.format("%02x", new Integer(b & 0xff)));
} return sb.toString();
}
方法五
/**
* 将byte数组转换成16进制字符串
*
* @param src
* @return
*/
private static String bytesToHexString(byte[] src) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
sb.append(0);
}
sb.append(hv);
}
return sb.toString();
}
3.16进制字符串转换为byte[]
方法一
/**
* 将16进制字符串转换为byte[]
* @explain 16进制字符串不区分大小写,返回的数组相同
* @param hexString
* 16进制字符串
* @return byte[]
*/
public static byte[] fromHexString(String hexString) {
if (null == hexString || "".equals(hexString.trim())) {
return new byte[0];
} byte[] bytes = new byte[hexString.length() / 2];
// 16进制字符串
String hex;
for (int i = 0; i < hexString.length() / 2; i++) {
// 每次截取2位
hex = hexString.substring(i * 2, i * 2 + 2);
// 16进制-->十进制
bytes[i] = (byte) Integer.parseInt(hex, 16);
} return bytes;
}
方法二
/**
* 将16进制转换为byte[]
* @param hexStr
* @return
*/
public static byte[] fromHex(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
方法三:
public static byte[] toByteArray(String data) {
if (data == null) {
return new byte[] {};
}
if (data.length() == 0) {
return new byte[] {};
}
while (data.length() < 2) {
data = "0" + data;
}
if (data.substring(0, 2).toLowerCase().equals("0x")) {
data = data.substring(2);
}
if (data.length() % 2 == 1) {
data = "0" + data;
}
data = data.toUpperCase();
byte[] bytes = new byte[data.length() / 2];
String hexString = "0123456789ABCDEF";
for (int i = 0; i < bytes.length; i++) {
int byteConv = hexString.indexOf(data.charAt(i * 2)) * 0x10;
byteConv += hexString.indexOf(data.charAt(i * 2 + 1));
bytes[i] = (byte) (byteConv & 0xFF);
}
return bytes;
}
4.测试
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"Marydon\",\"website\":\"http://www.cnblogs.com/Marydon20170307\"}";
byte[] bytes = json.getBytes("utf-8");
System.out.println("字节数组为:" + Arrays.toString(bytes));
System.out.println("byte数组转16进制之方法一:" + toHexString(bytes));
System.out.println("byte数组转16进制之方法二:" + ByteUtils.toHexString2(bytes));
System.out.println("byte数组转16进制之方法三:" + ByteUtils.toHexString3(bytes));
System.out.println("byte数组转16进制之方法四:" + ByteUtils.toHexString4(bytes));
System.out.println("==================================");
String str = "7b226e616d65223a224d617279646f6e222c2277656273697465223a22687474703a2f2f7777772e636e626c6f67732e636f6d2f4d617279646f6e3230313730333037227d";
System.out.println("转换后的字节数组:" + Arrays.toString(fromHexString(str)));
System.out.println(new String(fromHexString(str), "utf-8"));
}
20200520补充
1B=8b,也就是1byte=8bit;
1KB=1024B;
1MB=1024KB;
1GB=1024MB;
1TB=1024GB
bit是计算机最小的存储单元,只能存储0和1,是Binary digit(二进制数位)的缩写,意为“位”或“比特”,也就是二进制。
java byte数组与16进制间的相互转换的更多相关文章
- C# byte数组与16进制间的相互转换
1.byte数组转16进制字符串 /// <summary> /// 将一个byte数组转换成16进制字符串 /// </summary> /// <param na ...
- java字节数组和16进制之间的转换
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ pac ...
- BYTE数组与16进制字符串互转
//字节数组转换为HEX 字符串const string Byte2HexString(const unsigned char* input, const int datasize) { ]; ; j ...
- 加密算法使用(二):使用MD5加密字符串(另:byte数组转16进制自动补零方法写法)
public static void main(String args[]) throws NoSuchAlgorithmException { String s = new String(" ...
- byte数组转16进制 输出到文件
try { File file = new File(Environment.getExternalStorageDirectory(),"shuju2"); if(!file.e ...
- Java中byte与(16进制)字符串的互相转换
java中byte用二进制表示占用8位,而我们知道16进制的每个字符需要用4位二进制位来表示,所以我们就可以把每个byte转换成两个相应的16进制字符,即把byte的高4位和低4位分别转换成相应的16 ...
- java中把字节数组转换为16进制字符串
把字符串数组转换为16进制字符串 import java.security.MessageDigest; public class StringUtil { public StringUtil() { ...
- C#//字节数组转16进制字符串
//字节数组转16进制字符串 private static string byteToHexStr(byte[] bytes,int length) { string returnStr = &quo ...
- Java中字符串转为16进制表示
Java中字符串转为16进制表示 String str = "鲸"; char[] chars = "0123456789ABCDEF".toCharArray ...
随机推荐
- 判断listview滑动方向的代码片段
mListView.setOnScrollListener(new OnScrollListener() { private int lastIndex = 0; @Override public v ...
- 解决Installation error: INSTALL_FAILED_VERSION_DOWNGRADE错误
Installation error: INSTALL_FAILED_VERSION_DOWNGRADE 说明你手机里已经装的软件版本比你要安装的软件版本要高,所以不能安装. 你只要删除你安装的应用便 ...
- WSL(Windows Subsystem for Linux)的安装与使用
有关WSL的介绍这里就不做解释了.另外,本文仅适用于win10 build 16215以及之后的版本,之前的版本可参考官方链接. (可使用“winver”命令查看windows版本号) 安装: 1. ...
- [转]PHP 汉字转拼音
转自: https://git.oschina.net/wapznw/php-pinyin <?php /** * @package default * @copyright php-pinyi ...
- PHP: Short URL Algorithm Implementation
1.http://www.snippetit.com/2009/04/php-short-url-algorithm-implementation/ The following code is wri ...
- SQL Server 数据库项目
ylbtech-.NET Framework: SQL Server 数据库项目 SQL Server 数据库项目 类型:SQL Server 用于创建 SQL Server 数据库的项目 1. 新建 ...
- RxJava RxBinding RxView 控件事件 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- CSS框架BluePrint
做惯了后台程序的我们,是否对前端编程有兴趣么,通过CSS框架,使我们很容易的开发出基于Div+CSS布局的页面来,今天让我们了解下大名鼎鼎的blueprint CSS框架吧! 它的官方网站:http: ...
- Bootstrap风格button
一直非常喜欢Bootstrap的按钮风格,仿照Bootstrap做了一套按钮.在ie6/7/8/9/10/11.chrome.firefox下能正常使用. ie6/7/8不支持css3的样式.按钮在这 ...
- Python机器学习——线性模型
http://www.dataguru.cn/portal.php?mod=view&aid=3514 摘要 : 最近断断续续地在接触一些python的东西.按照我的习惯,首先从应用层面搞起, ...