欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

16进制字符类型与16进制相互转换

程序员文章站 2024-03-18 14:46:10
...
char str[]="2b7e151628aed2a6abf7158809cf4f3c" ;

    char key[32];

strtoHex(str,key);

//转换之后位数减半  32——16


void strtoHex(char *str,char * hex)//字符类型转成16进制  
{
             char ch;
             int     i=0, by = 0;
                                         
   while(i < 64 && * str)        //保证到str结尾
                      // the maximum key length is 32 bytes(256 bits) and
    {                           // hence at most 64 hexadecimal digits
        ch = toupper(* str++);   // process a hexadecimal digit
 
        if(ch >= '0' && ch <= '9')
            by = (by << 4) + ch - '0';
        else if (ch >= 'A' && ch <= 'F')
            by = (by << 4) + ch - 'A' + 10;
        else                    // error if not hexadecimal
        {
            printf( "key must be in hexadecimal notation\n" );
            exit(0);
        }

        // store a key byte for each pair of hexadecimal digits
        if(i++ & 1)
            hex[i / 2 - 1] = by & 0xff;           
      }
}




void hextoStr(char *hex,char * str)//16进制转成字符类型
{
    int i=0, by = 0;

   while(i < 32 && * hex)        // the maximum key length is 32 bytes(256 bits) and
    {                           // hence at most 64 hexadecimal digits
        by = * hex ;              // process a hexadecimal digit(high)
                         by=by>>4 &0x0f;
        if(by >= 0 && by <= 9)
            * str++ = by + '0' ;
        else if (by >= 0x0A && by <= 0x0F)
            * str++ = by -  10+ 'A' ;
        by = * hex++;            // process a hexadecimal digit(low)
                         by=by &0x0f;
        if(by >= 0 && by <= 9)
            * str++ = by + '0' ;
        else if (by >= 0x0A && by <= 0x0F)
            * str++ = by -  10+ 'A' ;
                        i++;
      }
}