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

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

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;
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值