Convert two ASCII Hexadecimal Characters (Two ASCII bytes) in one byte

后端 未结 6 2350
余生分开走
余生分开走 2020-12-18 13:08

I want to convert two ASCII bytes to one hexadecimal byte. eg.

0x30 0x43 => 0x0C , 0x34 0x46 => 0x4F ...

The ASCII bytes are a number bet

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 13:29

    It's works, but could be much optimized !

    inline uint8_t  twoAsciiByteToByte(const std::string& s)
    {
        uint8_t r = 0;
    
        if (s.length() == 4)
        {
            uint8_t a = asciiToByte(s[0]);
            uint8_t b = asciiToByte(s[1]);
            uint8_t c = asciiToByte(s[2]);
            uint8_t d = asciiToByte(s[3]);
    
            int h = (a * 10 + b);
            int l = (c * 10 + d);
    
            if (s[0] == '3')
                h -= 30;
            else if (s[0] == '4')
                h -= 31;
    
            if (s[2] == '3')
                l -= 30;
            else if (s[2] == '4')
                l -= 31;
    
            r = (h << 4) | l;
        }
    
        return r;
    }
    

提交回复
热议问题