Hex编码

Hex编码是一种用16个字符表示任意二进制数据的方法

C语言实现

利用sprintf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void toHex(const unsigned char *input, char *output, size_t len) {
for (size_t i = 0; i < len; i++) {
// 将每个字节转换为两位十六进制数
sprintf(output + (i * 2), "%02x", input[i]);
}
output[len * 2] = '\0'; // 确保输出字符串以空字符结尾
}


int main(){
const char *str = "你好";
char ret[100]={0};
to_Hex(str,ret,strlen(str));
printf("%s",ret);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void toHex(const unsigned char *input, char *output, size_t len) {
for (size_t i = 0; i < len; i++) {
// 将每个字节转换为两位十六进制数
char temp[3];
sprintf(temp, "%02x", input[i]);
strcat(output,temp);
}
output[len * 2] = '\0'; // 确保输出字符串以空字符结尾
}

int main(){
const char *str = "你好";
char *ret= (char *)malloc(strlen(str)*2+1);
memset(ret,0,strlen(str)*2+1);
toHex(str,ret,strlen(str));
printf("%s",ret);
}

手搓代码

1
2
3
4
5
6
7
8
void to_Hex(const unsigned char *str,char *ret,int len){
char index_table[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
for (int i = 0; i < len; ++i) {
ret[i*2] = index_table[str[i] >> 4];
ret[i*2+1] = index_table[str[i] & 0xF];
}
ret[len*2]='\0';
}
1
2
3
4
5
6
7
8
void to_Hex(const unsigned char *str,char *ret,int len){
for (int i = 0; i < len; ++i) {
ret[i*2] = ((str[i] >> 4) >= 0xa) ? ( (str[i] >> 4) + 65) : ((str[i] >> 4) + 48);
ret[i*2+1] = ((str[i] & 0xF) >= 0xa) ? ((str[i] & 0xF) + 65) : ((str[i] & 0xF) + 48);
}
ret[len*2]='\0';
}

Java实现

使用HexFormat.of().formatHex()

参数是byte[]类型,返回值是String类型。

1
2
3
4
5
6
7
8
9
10
public class Test {
public static void main(String[] args) {
byte[] numarr = {'a','b','c','d','e','f','g','h'};
String result = HexFormat.of().formatHex(numarr);
System.out.println(result);
}
}

>>>
6162636465666768

移位实现

1
2
3
4
5
6
7
8
9
public String hex(){
char[] result = new char[data.length*2];
int c = 0;
for(byte b:data){
result[c++] = HEX_DIGITS[ (b>>4) & 0xf]; //保留高位
result[c++] = HEX_DIGITS[b & 0xf]; //保留低位
}
return new String(result);
}