十六进制元素数组与字符串相互转换(C语言)
0x00 前言
文章中的文字可能存在语法错误以及标点错误,请谅解;
如果在文章中发现代码错误或其它问题请告知,感谢!
0x01 字符串化成十六进制数组
将十六进制的数组转化成同样值的字符串函数如下:
int StringToBuff(char *str,unsigned char *OutputBuff)
{
char *p = NULL;
char High = 0;
char Low = 0;
int i = 0;
int Len = 0;
int count = 0;
p = str;
Len = strlen(p);
while(count < (Len/2))
{
High = ((*p > '9') && ((*p <= 'F') || (*p <= 'f')))?*p - 48 - 7 : *p - 48;
Low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f')))? *p - 48 - 7 : *p - 48;
OutputBuff[count] = ((High & 0x0f) << 4 | (Low & 0x0f));
p ++;
count ++;
}
//判断字符串长度是否为奇数
if(0 != Len%2)
{
OutputBuff[count++] = ((*p >'9')&&(*p<='F')||(*p<='f'))?*p-48-7:*p-48;
}
return Len/2 + Len%2;
}
0x02 十六进制数组转化成字符串
int ArrayToStr(unsigned char *Buff, unsigned int BuffLen, char *OutputStr)
{
int i = 0;
char TempBuff[128] = { 0};
char strBuff[256] = { 0};
for(i = 0; i<BuffLen;i++)
{
sprintf(TempBuff,"%02x",Buff[i]);//以十六进制格式输出到TempBuff,宽度为2
strncat(strBuff,TempBuff,BuffLen*2);//将TempBuff追加到strBuff结尾
}
strncpy(OutputStr, strBuff, BuffLen*2); //将strBuff复制到OutputStr
return BuffLen*2;
}
0x03 举例
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
unsigned char ArrayHex[16] = { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f, 0x7b, 0x8d, 0x9e, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
char *strCom = "1a2b3c4d5e6f7a8b9c1011121314";
int main(int argc, const char *argv)
{
int i= 0;
int outlen = 0;
char str[33] = { 0};
unsigned char out[33] = { 0};
ArrayToStr(ArrayHex, 16, str);
printf("after ArrayToStr :%s\n",str);
outlen = StringToBuff(strCom, out);
printf("after StringToBuff\n");
for(i= 0; i< outlen; i++)
{
printf("%02X ", out[i]);
}
printf("\n");
return 0;
}
以上。
参考文档:
https://blog.csdn.net/zhemingbuhao/article/details/83111564
还没有评论,来说两句吧...