十六进制元素数组与字符串相互转换(C语言)

短命女 2023-06-27 03:52 92阅读 0赞

0x00 前言

文章中的文字可能存在语法错误以及标点错误,请谅解;

如果在文章中发现代码错误或其它问题请告知,感谢!

0x01 字符串化成十六进制数组

将十六进制的数组转化成同样值的字符串函数如下:

  1. int StringToBuff(char *str,unsigned char *OutputBuff)
  2. {
  3. char *p = NULL;
  4. char High = 0;
  5. char Low = 0;
  6. int i = 0;
  7. int Len = 0;
  8. int count = 0;
  9. p = str;
  10. Len = strlen(p);
  11. while(count < (Len/2))
  12. {
  13. High = ((*p > '9') && ((*p <= 'F') || (*p <= 'f')))?*p - 48 - 7 : *p - 48;
  14. Low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f')))? *p - 48 - 7 : *p - 48;
  15. OutputBuff[count] = ((High & 0x0f) << 4 | (Low & 0x0f));
  16. p ++;
  17. count ++;
  18. }
  19. //判断字符串长度是否为奇数
  20. if(0 != Len%2)
  21. {
  22. OutputBuff[count++] = ((*p >'9')&&(*p<='F')||(*p<='f'))?*p-48-7:*p-48;
  23. }
  24. return Len/2 + Len%2;
  25. }

0x02 十六进制数组转化成字符串

  1. int ArrayToStr(unsigned char *Buff, unsigned int BuffLen, char *OutputStr)
  2. {
  3. int i = 0;
  4. char TempBuff[128] = { 0};
  5. char strBuff[256] = { 0};
  6. for(i = 0; i<BuffLen;i++)
  7. {
  8. sprintf(TempBuff,"%02x",Buff[i]);//以十六进制格式输出到TempBuff,宽度为2
  9. strncat(strBuff,TempBuff,BuffLen*2);//将TempBuff追加到strBuff结尾
  10. }
  11. strncpy(OutputStr, strBuff, BuffLen*2); //将strBuff复制到OutputStr
  12. return BuffLen*2;
  13. }

0x03 举例

  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "string.h"
  4. unsigned char ArrayHex[16] = { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f, 0x7b, 0x8d, 0x9e, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
  5. char *strCom = "1a2b3c4d5e6f7a8b9c1011121314";
  6. int main(int argc, const char *argv)
  7. {
  8. int i= 0;
  9. int outlen = 0;
  10. char str[33] = { 0};
  11. unsigned char out[33] = { 0};
  12. ArrayToStr(ArrayHex, 16, str);
  13. printf("after ArrayToStr :%s\n",str);
  14. outlen = StringToBuff(strCom, out);
  15. printf("after StringToBuff\n");
  16. for(i= 0; i< outlen; i++)
  17. {
  18. printf("%02X ", out[i]);
  19. }
  20. printf("\n");
  21. return 0;
  22. }

以上。

参考文档:
https://blog.csdn.net/zhemingbuhao/article/details/83111564

发表评论

表情:
评论列表 (有 0 条评论,92人围观)

还没有评论,来说两句吧...

相关阅读