新闻  |   论坛  |   博客  |   在线研讨会
C语言 -- 字符串和十六进制的相互转换方式
电子禅石 | 2020-03-12 10:48:09    阅读:4098   发布文章

C语言的字符串操作并不像java,Csharp那样提供直接的方法,简单粗暴。所以,在转换的时候往往费力费时,近日做项目正好用到和java程序通讯,java发送过来的数据是十六进制数字组成的字符串,解析的时候颇费心思才算完成,所以,权在此做一笔记,方便以后查看,以及需要帮助的童鞋,当然,有问题欢迎随时交流,一同进步,欧耶!~
一、将数组转换为十六进制同值的字符串

   读取数组中的数字,打印成字符串的时候以2位大写的格式。

int arrayToStr(unsigned char *buf, unsigned int buflen, char *out)
{
    char strBuf[33] = {0};
    char pbuf[32];
    int i;
    for(i = 0; i < buflen; i++)
    {
        sprintf(pbuf, "%02X", buf[i]);
        strncat(strBuf, pbuf, 2);
    }
    strncpy(out, strBuf, buflen * 2);
    printf("out = %s\n", out);
    return buflen * 2;
}

二、将十六进制的字符串转换为十六进制数组

下面定义的字符串中的字符只能是0-F的字符,但是不区分大小写的,前面是安装两位为一个数字进行转换,最后一个数字如果还是两位的则正常转换,如果只剩一位的话则在前面补零输出。

int StringToHex(char *str, unsigned char *out, unsigned int *outlen)
{
    char *p = str;
    char high = 0, low = 0;
    int tmplen = strlen(p), cnt = 0;
    tmplen = strlen(p);
    while(cnt < (tmplen / 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;
        out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f));
        p ++;
        cnt ++;
    }
    if(tmplen % 2 != 0) out[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
   
    if(outlen != NULL) *outlen = tmplen / 2 + tmplen % 2;
    return tmplen / 2 + tmplen % 2;
}

三、将十进制字符串转化为十进制数组

int StringToCom(char *str, unsigned char *out, int *outlen)
{
    char *p = str;
    char high = 0, low = 0;
    int tmplen = strlen(p), cnt = 0;
    tmplen = strlen(p);
    if(tmplen % 2 != 0) return -1;
    while(cnt < tmplen / 2) //1213141516171819
    {
        out[cnt] = (*p - 0x30) * 10 + (*(++p) - 0x30);
        p++;
        cnt ++;
    }
    *outlen = tmplen / 2;
    return tmplen / 2;
}

四、简单的使用方法

定义的参数有些为unsigned char,是因为在定义为char的时候,转换为十六进制之后,负数在表示的时候,难看!

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
 
unsigned char ArrayCom[16] = {
    11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 26};
unsigned char ArrayHex[16] = {
    0x2c, 0x57, 0x8f, 0x79, 0x27, 0xa9, 0x49, 0xd3,
    0xb5, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
 
char *strHex = "01aa0304050607083f0add0c0d0e0f00";
char *strCom = "1D1213AB6FC1718B19202122232425A6";
 
int main(int argc, const char *argv)
{
    int cnt;
    char str[33] = {0};
    unsigned char out[33];
    arrayToStr(ArrayCom, 16, str);
   
    int outlen = 0;
    StringToHex(strCom, out, &outlen);
    for(cnt = 0; cnt < outlen; cnt ++)
    {
        printf("%02X ", out[cnt]);
    }
    putchar(10);
 
    return 0;
}

https://blog.csdn.net/zhemingbuhao/article/details/83111564

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

参与讨论
登录后参与讨论
属于自己的技术积累分享,成为嵌入式系统研发高手。
推荐文章
最近访客