C语言:直接可以用的16进制转字符串&字符串转16进制

1.16进制转字符串

unsigned char unicode_number[22]={0x00,0x31,0x00,0x37,0x00,0x38,0x00,0x31,0x00,0x31,
                                0x00,0x30,0x00,0x30,0x00,0x30,0x00,0x39,0x00,0x32,0x00,0x37};
unsigned char consumer_number[100]={0}; 
/***********************************************************************
* 功能:将一个十六进制字节串转换成ASCII码表示的十六进制字符串
* 输入参数:pHex----十六进制数字节串首地址
*                   pAscii---转换后ASCII码表示的十六进制字符串首地址
*                   nLen---要转换的十六进制数长度(字节数)
* 注:转换后的结果全部是大写ASCII码表示的十六进制数
*此部分百度的
************************************************************************/
void HexToAscii(unsigned char *pHex, unsigned char *pAscii, int nLen)
{
    unsigned char Nibble[2];
    unsigned int i,j;
    for (i = 0; i < nLen; i++){
        Nibble[0] = (pHex[i] & 0xF0) >> 4;
        Nibble[1] = pHex[i] & 0x0F;
        for (j = 0; j < 2; j++){
            if (Nibble[j] < 10){            
                Nibble[j] += 0x30;
            }
            else{
                if (Nibble[j] < 16)
                    Nibble[j] = Nibble[j] - 10 + 'A';
            }
            *pAscii++ = Nibble[j];
        }               // for (int j = ...)
    }           // for (int i = ...)
}
void main(void) 
{
    //依旧用串口一进行实验
    P3M0 = 0X00;
    P3M1 = 0X00;

    UART1_config();             //串口初始化
    uart1_printf("UART1 is good! \r\n");
    
    HexToAscii(unicode_number, consumer_number, 22);
    
    uart1_printf(consumer_number);
    while(1);
}

运行效果:

C语言:直接可以用的16进制转字符串&字符串转16进制_第1张图片
串口助手字符显示

转载来源: https://blog.csdn.net/sinat_41577729/article/details/86775583

2.字符串转16进制

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

char *strCom = "1D1213AB6FC1718B19202122232425A6";

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 main(int argc, const char *argv)
{
    int cnt;
    unsigned char out[33];
    
    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

你可能感兴趣的:(C语言:直接可以用的16进制转字符串&字符串转16进制)