c++clow-level-code

How to form an ASCII(Hex) number using 2 Chars?


I have char byte[0] = '1' (H'0x31)and byte[1] = 'C'(H'0x43)

I am using one more buffer to more buff char hex_buff[0] .i want to have hex content in this hex_buff[0] = 0x1C (i.e combination of byte[0] and byte[1])

I was using below code but i realized that my code is valid for the hex values 0-9 only

char s_nibble1 = (byte[0]<< 4)& 0xf0;

char s_nibble2 =  byte[1]& 0x0f;

hex_buff[0] = s_nibble1 | s_nibble2;// here i want to have 0x1C instead of 0x13


Solution

  • A possible way to do it, without dependencies with other character manipulation functions:

    char hex2byte(char *hs)
    {
        char b = 0;
        char nibbles[2];
        int i;
    
        for (i = 0; i < 2; i++) {
            if ((hs[i] >= '0') && (hs[i] <= '9')) 
                nibbles[i] = hs[i]-'0';
            else if ((hs[i] >= 'A') && (hs[i] <= 'F')) 
                nibbles[i] = (hs[i]-'A')+10;
            else if ((hs[i] >= 'a') && (hs[i] <= 'f')) 
                nibbles[i] = (hs[i]-'a')+10;
            else 
                return 0;
        }
    
        b = (nibbles[0] << 4) | nibbles[1];
        return b;
    }
    

    For example: hex2byte("a1") returns the byte 0xa1.

    In your case, you should call the function as: hex_buff[0] = hex2byte(byte).