C/C++ 十六進位char*與Binary char*相互轉換,charbinary

來源:互聯網
上載者:User

C/C++ 十六進位char*與Binary char*相互轉換,charbinary
1. 十六進位char* 轉 Binary char*

例如:“fedcba9876543210”
轉換為:char bin[8] ={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}形式。
代碼:

/*兩個字元轉換成一個字元,長度為原來的1/2*/static void Hex2Char(char *szHex, unsigned char *rch){    int i;    for(i=0; i<2; i++)    {        if(*(szHex + i) >='0' && *(szHex + i) <= '9')            *rch = (*rch << 4) + (*(szHex + i) - '0');        else if(*(szHex + i) >='a' && *(szHex + i) <= 'f')            *rch = (*rch << 4) + (*(szHex + i) - 'a' + 10);        else            break;    }}
/*十六進位char* 轉 Binary char*函數*/void HexStr2CharStr( char *pszHexStr, int iSize,  char *pucCharStr){    int i;    unsigned char ch;    if (iSize%2 != 0) return;    for(i=0; i<iSize/2; i++)    {        Hex2Char(pszHexStr+2*i, &ch);        pucCharStr[i] = ch;    }}
2. Binary char* 轉 十六進位char*

例如:char bin[8] ={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
轉換為:“fedcba9876543210”
代碼:

/*單個字元轉十六進位字串,長度增大2被*/static void Char2Hex(unsigned char ch, char *szHex){    int i;    unsigned char byte[2];    byte[0] = ch/16;    byte[1] = ch%16;    for(i=0; i<2; i++)    {        if(byte[i] >= 0 && byte[i] <= 9)            szHex[i] = '0' + byte[i];        else            szHex[i] = 'a' + byte[i] - 10;    }    szHex[2] = 0;}
/*字串轉換函式,中間調用上面的函數*/void CharStr2HexStr( char *pucCharStr, int iSize,  char *pszHexStr){    int i;    char szHex[3];    pszHexStr[0] = 0;    for(i=0; i<iSize; i++)    {        Char2Hex(pucCharStr[i], szHex);        strcat(pszHexStr, szHex);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.