字符与代表数据的转化

目的

在与设备交互当中,大都以十六进制的数进行交互。
而显示给用户时,是以字符的形式显示。
这中间就需要字符与其所代表的数值的转化,比如:
‘0F’---->0x0F
这怎么实现呢,一个是字符,另一个是数字,在计算机当中存的东西是不一样的,完全两类东西。
字符在计算机是通过ASCII码保存的,即:
由于计算机是美国人发明的,所以对于英文字符,美国人制定了一个字符和二进制对应的码表,这个码表就是ASCII码,即美国标准信息交换码(American Standard Code for Information Interchange)。
ASCII字符编码具体对应关系如下:
在这里插入图片描述

其本质也是数字,而且都是按顺序排列的,那这样就简单,开始实现:

实现过程

int MainWindow::char2bits(char ch)
{
    
    
    int bits = 0;
    if (ch >= 'a' && ch <= 'z')
    {
    
    
        bits = ch - 'a' + 10;
    }
    else if (ch >= 'A' && ch <= 'Z')
    {
    
    
        bits = ch - 'A' + 10;
    }
    else if (ch >= '0' && ch <= '9')
    {
    
    
        bits = ch - '0';
    }
    else
    {
    
    
        bits = -1;
    }
    return bits;
}
int MainWindow::hex2bytes(const char *hex, char *bytes, int size)
{
    
    
    int len = strlen(hex);
    int nbytes = (len + 1) / 3;
    if (nbytes > size)
    {
    
    
        return -1;
    }
    int n;
    for (n = 0; n != nbytes; ++ n)
    {
    
    
        int lndx = n * 3;
        int rndx = lndx + 1;
        int lbits = char2bits(hex[lndx]);
        int rbits = char2bits(hex[rndx]);
        if (lbits == -1 || rbits == -1)
        {
    
    
            return -1;
        }
        bytes[n] = (lbits << 4) | rbits;
    }
    return nbytes;
}
void MainWindow::on_btnTest_clicked()
{
    
    
    const char *hex = "07 0A 02 10 03 00 00 00 00 00";
       char stream[10];
       int nbytes = hex2bytes(hex, stream, 10);
       if (nbytes != -1)
       {
    
    
           int i = 0;
           for ( ; i < nbytes; ++ i)
           {
    
    
               qDebug("%02x ", stream[i]);
           }
       }
}

运行情况:
在这里插入图片描述

总结

一开始想时,感觉有些复杂,知道其本质了就简单了了,什么本质,字符在计算机里就是存在数字,这种对应关系就是ASCII表。
比如字符 ‘B’ 其对应的数值应该为11,那其:‘B’-‘A’=1,那再加上10,不就是11了吗?
再比如’1’,其对应的数据应该为1,那’1’-‘0’=1
一切字符都是两个字节的数值,并且是按顺序来的,理解了这个本质,就非常简单了。
最后以一图进行总结:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/maokexu123/article/details/131457987
今日推荐