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进制间的相互转换的更多相关文章

  1. C# byte数组与16进制间的相互转换

      1.byte数组转16进制字符串 /// <summary> /// 将一个byte数组转换成16进制字符串 /// </summary> /// <param na ...

  2. java字节数组和16进制之间的转换

    /* * To change this template, choose Tools | Templates * and open the template in the editor. */ pac ...

  3. BYTE数组与16进制字符串互转

    //字节数组转换为HEX 字符串const string Byte2HexString(const unsigned char* input, const int datasize) { ]; ; j ...

  4. 加密算法使用(二):使用MD5加密字符串(另:byte数组转16进制自动补零方法写法)

    public static void main(String args[]) throws NoSuchAlgorithmException { String s = new String(" ...

  5. byte数组转16进制 输出到文件

    try { File file = new File(Environment.getExternalStorageDirectory(),"shuju2"); if(!file.e ...

  6. Java中byte与(16进制)字符串的互相转换

    java中byte用二进制表示占用8位,而我们知道16进制的每个字符需要用4位二进制位来表示,所以我们就可以把每个byte转换成两个相应的16进制字符,即把byte的高4位和低4位分别转换成相应的16 ...

  7. java中把字节数组转换为16进制字符串

    把字符串数组转换为16进制字符串 import java.security.MessageDigest; public class StringUtil { public StringUtil() { ...

  8. C#//字节数组转16进制字符串

    //字节数组转16进制字符串 private static string byteToHexStr(byte[] bytes,int length) { string returnStr = &quo ...

  9. Java中字符串转为16进制表示

    Java中字符串转为16进制表示 String str = "鲸"; char[] chars = "0123456789ABCDEF".toCharArray ...

随机推荐

  1. Notification详解(含工具类)

                                                                     昨天一天只写了两篇文章,效率超低.追其原因呢,其实我一直在研究noti ...

  2. linux 7z 命令编译安装,mac安装p7zip

    linux 7z 命令编译安装 7zip是一个开源的压缩软件  7z格式是压缩率最高的格式 服务器备份 数据几个g 要是tar压缩下载的话 时间太长  7zip压缩出来体积很小 首先安装 我这是 ce ...

  3. GPS定位基本原理浅析

    位置服务已经成为越来越热的一门技术,也将成为以后所有移动设备(智能手机.掌上电脑等)的标配.而定位导航技术中,目前精度最高.应用最广泛的,自然非GPS莫属了.网络上介绍GPS原理的专业资料很多,而本文 ...

  4. InnoDB Record, Gap, and Next-Key Locks

    InnoDB has several types of record-level locks including record locks, gap locks, and next-key locks ...

  5. hyper-v 用户无法再 创建外部配置存储 0x80070005

    windows server 2008R2 刚安装的hyper-v 重启过. 修改配置文件到d:\Hyper-V目录下, hyper-V 创建 服务器遇到错误 操作失败 创建外部配置存储:一般性拒绝访 ...

  6. knockout示例

    最近项目需要用到knockout js,有关knockout的介绍网上已经很多很多了,但是很少有比较全面的示例,于是乎我就自己做了一个小demo,已备以后查阅.knockout经常和knockout. ...

  7. [leetcode]Text Justification @ Python

    原题地址:https://oj.leetcode.com/problems/text-justification/ 题意: Given an array of words and a length L ...

  8. [leetcode]Validate Binary Search Tree @ Python

    原题地址:https://oj.leetcode.com/problems/validate-binary-search-tree/ 题意:检测一颗二叉树是否是二叉查找树. 解题思路:看到二叉树我们首 ...

  9. js命名空间写法

    很早知道这种写法,由于基础面向对象不够扎实一直在回避,但是面对整站这种方法还是有必要会 <div id="div1">111</div> <div i ...

  10. 简单使用Google Analytics监控网站浏览行为

    之前对网页做用户转化率调查这块,找到了谷歌GA事件,现在有时间对使用方法和遇到问题做个简单记录.官方文档其实也介绍的比较清楚,可以查看官方文档. 首先,在官网申请UA-id,然后在主页加入如下代码: ...