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

后端 未结 6 2388
余生分开走
余生分开走 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:41

    Converting 2 hex chars to a byte is done in two steps:

    1. Convert char a and b to their number (e.g. 'F' -> 0xF), which is done in two big if else branches, that check if the char is in the range '0' to '9', 'A' to 'F' or 'a' to 'f'.

    2. In the 2nd step the two numbers are joined by shifting a (largest value is 0xF (0b0000_FFFF)) 4 to the left (a << 4 -> 0b1111_0000) and then apply the bitwise or operation on a and b ((a << 4) | b):

    a: 0000_1111
    b: 1111_0000
    -> 1111_1111
    
    #include 
    #include 
    
    #define u8 uint8_t
    #define u32 uint32_t
    
    u8 to_hex_digit(char a, char b) {
        u8 result = 0;
    
        if (a >= 0x30 && a <= 0x39) {
            result = (a - 0x30) << 4;
        } else if (a >= 0x41 && a <= 0x46) {
            result = (a - 0x41 + 10) << 4;
        } else if (a >= 0x61 && a <= 0x7A) {
            result = (a - 0x61 + 10) << 4;
        } else {
            printf("invalid hex digit: '%c'\n", a);
        }
    
        if (b >= 0x30 && b <= 0x39) {
            result |= b - 0x30;
        } else if (b >= 0x41 && b <= 0x46) {
            result |= b - 0x41 + 10;
        } else if (b >= 0x61 && b <= 0x7A) {
            result |= b - 0x61 + 10;
        } else {
            printf("invalid hex digit: '%c'\n", b);
        }
    
        return result;
    }
    
    u32 main() {
        u8 result = to_hex_digit('F', 'F');
        printf("0x%X (%d)\n", result, result);
    
        return 0;
    }
    

提交回复
热议问题