Java版:
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
c语言版:
/**
* hex格式char转二进制
*/
unsigned char hex_of_char(char c) {
unsigned char tmp = 0;
if(c >= '0' && c <= '9') {
tmp = (c - '0');
}
else if(c >= 'A' && c <= 'F') {
tmp = (c - 'A' + 10);
}
else if(c >= 'a' && c <= 'f') {
tmp = (c - 'a' + 10);
}
return tmp;
}
static char g_hex_map_table[] = "0123456789ABCDEF";
/**
* 字节数组转hex格式字符串
* @param print_buf: 十六进制字符串buffer
* @param print_buf_len: 十六进制字符串buffer长度
* @param bytes: 二进制数据
* @param bytes_len: 二进制数据长度
*/
char* bytes_to_hex_string(
char* print_buf,
int print_buf_len,
const unsigned char* bytes,
int len) {
int i = 0;
/**
* 入参校验
*/
if(print_buf == NULL || bytes == NULL || (len * 2 + 1) > print_buf_len) {
return NULL;
}
for(i = 0; i < len; i++) {
print_buf[i * 2] = g_hex_map_table[(bytes[i] >> 4) & 0x0F];
print_buf[i * 2 + 1] = g_hex_map_table[(bytes[i]) & 0x0F];
}
/**
* 填充字符串结束符
*/
print_buf[i * 2] = '\0';
/**
* 返回目标地址
*/
return print_buf;
}
/**
* hex格式字符串转字节数组
* @param hex_string: 十六进制字符串
* @param hex_string_len: 十六进制字符串长度
* @param bytes: 二进制数据存储空间
* @param bytes_len: 目标空间长度
*/
int hex_string_to_bytes(
char* hex_string,
int hex_string_len,
unsigned char* bytes,
int bytes_len) {
int i = 0;
/**
* 校验十六进制字符串长度必须偶数,并且目标存储空间必须足够存放转换后的二进制数据
*/
if((hex_string_len % 2 != 0) || (bytes_len * 2 < hex_string_len)) {
return -1;
}
for(i = 0; i < hex_string_len; i += 2) {
bytes[i/2] = ((hex_of_char(hex_string[i]) << 4) & 0xF0) |
(hex_of_char(hex_string[i + 1]) & 0x0F);
}
return 1;
}