c++ 将十六进制转换成汉字

本文提供了一个C++程序示例,展示了如何将十六进制字符串转换为字符数组,并反向进行转换的方法。通过使用自定义函数`ch2hex`来解析十六进制字符,以及`solve`函数实现字符串到字符数组的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include <string.h>
#include<algorithm>
#include<cstdlib>
using namespace std;
unsigned char ch2hex(char ch)
    {
    static const char *hex="0123456789ABCDEF";
    for(unsigned char i=0;i!=16;++i)
        if(ch==hex[i])
            return i;
    return 0;
    }
char* solve(char *dest,const char *src)
    {
    int i=0;
    int cnt=0;
    unsigned char*d=(unsigned char*)dest;
    while(*src)
        {
        if(i&1)
            {
            d[cnt++]|=ch2hex(*src);
            }
        else
            {
            d[cnt]=ch2hex(*src)<<4;
            }
        src++;
        i++;
        }
    return dest;
    }
string tohex(const string& str)
    {
    string ret;
    static const char *hex="0123456789ABCDEF";
    for(int i=0;i!=str.size();++i)
        {
        ret.push_back(hex[(str[i]>>4)&0xf]);
        ret.push_back( hex[str[i]&0xf]);
        }
    return ret;
    }
int main()
    {
    cout<<tohex("中国人")<<endl;
    char dest[24]={0},src[]="D6D0B9FAC8CB0D0A";
    puts(solve(dest,src));
    system("pause");
    return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值