C語言將16進制字符數組轉化為16進制數值數組


1.背景

有時會出現這樣一種情景:我們需要接收十六進制數用於數據處理,但收到的不是hex而是字符類型,
即想要的是0x8c而收到的是0x38 0x63("8"和“c”對應的ASCII碼),這時便需要對其進行轉化。

圖片名稱

2.代碼

/**
  * OS:windows 10
  * IDE:VS2021
  * Language:c/c++
  */

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

int HexStr2HexNum(char* HexStrArray, int len, unsigned char* HexNumArray);

int main(){
    char str1[] = "8c5def";
    //char str1[] = "F95dev";  //you can check with this wrong format hex string
    char* str = str1;
    unsigned char HexNumArray[3];

    int num = HexStr2HexNum(str, strlen(str), HexNumArray);
    if (num == 0)
    {
        for (int i = 0; i < sizeof(HexNumArray); i++)
            printf("%x ", HexNumArray[i]);
        printf("\n");
    }

}

/**
  * @brief  Convert hex String to hex number.
  * @param  HexStrArray: pointer to the hex string array
  * @param  len: length of the hex string.
  * @param  HexNumArray: pointer to the hex number array
  * @retval Function status
             This parameter can be one of the following values:
               @arg 0:The conversion run correctly.
               @arg -1:The conversion run incorrectly.
  */
int HexStr2HexNum(char* HexStrArray, int len, unsigned char* HexNumArray)
{
    int j = 0;
    for (int i = 0; i < len; i += 2)
    {   
        char HIGH_BYTE=0;
        char LOW_BYTE=0;
        //high 4
        if (HexStrArray[i] > 0x30 && HexStrArray[i] < 0x3A) 
        {
            HIGH_BYTE = HexStrArray[i] - 0x30;
        }
        else if (HexStrArray[i] > 0x41 && HexStrArray[i] < 0x47)
        {
            HIGH_BYTE = HexStrArray[i] - 0x37;
        }
        else if (HexStrArray[i] > 0x61 && HexStrArray[i] < 0x67)
        {
            HIGH_BYTE = HexStrArray[i] - 0x57;
        }
        else
        {
            printf("Please make sure the format of Hex String is correct!\r\n");
            printf("The wrong char is \"%c\", and its number is % d\r\n", HexStrArray[i],i);
            return -1;
        }

        //low 4
        if (HexStrArray[i + 1] > 0x30 && HexStrArray[i + 1] < 0x3A) 
        {
            LOW_BYTE = HexStrArray[i + 1] - 0x30;
        }
        else if (HexStrArray[i + 1] > 0x41 && HexStrArray[i + 1] < 0x47)
        {
            LOW_BYTE = HexStrArray[i + 1] - 0x37;
        }
        else if (HexStrArray[i + 1] > 0x61 && HexStrArray[i + 1] < 0x67)
        {
            LOW_BYTE = HexStrArray[i + 1] - 0x57;
        }
        else
        {
            printf("Please make sure the format of Hex String is correct!\r\n");
            printf("The wrong char is %c ,and its number is %d\r\n", HexStrArray[i+1], i+1);
            return -1;
        }

        HexNumArray[j] &= 0x0F;
        HexNumArray[j] |= (HIGH_BYTE << 4) ;
        HexNumArray[j] &= 0xF0;
        HexNumArray[j] |= LOW_BYTE;
        j++;
    }
    return 0;
}

參考:
C語言如何將十六進制字符串轉為十六進制Byte


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM