字节、二进制、十六进制转换输出

//将字节转换成二进制输出

std::string ToBinaryString(const unsigned char* buf,int len)
{
    int output_len = len*8;
    std::string output;
    const char* m[] = {"0","1"};

    for(int i = output_len - 1,j = 0; i >=0 ; --i,++j)
    {
        output.append(m[((unsigned char)buf[j/8] >> (i % 8)) & 0x01],1);
    }
    return output;

}
//将十六进制数字字符串转成字节
int ConvertHexToBin(char *hexkey, unsigned char *key, int *keylen)
{
    char *cp, ch;
    int i = 0, by = 0;

    cp = hexkey;    // this is a pointer to the hexadecimal key digits

    while(*cp) 
    {
        ch = toupper(*cp++);    // 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
            return 0;

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

    *keylen = i / 2;    
    return 1;
}

//将字节转成十六进制数字字符串
int ConvertBinToHex(unsigned char *key, int keylen, char *hexkey)
{
    int i=0;
    if(hexkey == NULL)
        return 0;

    for(i=0; i<keylen; i++)
        sprintf(hexkey+i*2, "%02X", key[i]);

    return 1;
}
 

猜你喜欢

转载自blog.csdn.net/struborn_b/article/details/106444160