ASCII格式的16进制字符串转到ASCII字符串

本程序实现的功能是将ASCII格式的16进制字符串转到ASCII字符串。例如,字符串“6a61636b”可转化为jack。

啥都不说了,先给程序

//
//  main.cpp
//  hex_2_asc
//
//  Created by 刘鹏 on 14-3-18.
//  Copyright (c) 2014年 刘鹏. All rights reserved.
//
// 

#include <iostream>
#include <string>
using namespace std;

int main(int argc, const char * argv[])
{
    string instr,outstr;
    char tmp;
    int big,small,final_dec;
    cout<<"input"<<endl;
    cin>>instr;
    for (string::iterator it = instr.begin();
         it != instr.end(); it++)
    {
        
        // char类型的16进制先转化为10进制的int
        //  第1个16进制数
        final_dec = 0;
        if (*it >= 'a' && *it <= 'f')
        {
            big = *it - 87;
        }
        else if (*it >= 'A' && *it <= 'F')
        {
            big = *it - 55;
        }
        else if (*it >= '0' && *it <= '9')
        {
            big = *it - 48;
        }
        else
            big = 0;
        final_dec = final_dec + (big<<4);
        it++;
        
        //  第2个16进制数
        if (*it >= 'a' && *it <= 'f')
        {
            small = *it - 87;
        }
        else if (*it >= 'A' && *it <= 'F')
        {
            small = *it - 55;
        }
        else if (*it >= '0' && *it <= '9')
        {
            small = *it - 48;
        }
        else
            small = 0;
        final_dec += small;
        if (final_dec > 255)
        {
            final_dec = 255;
        }
        tmp = final_dec;
        outstr.push_back(tmp);
    }
    cout<<"translated"<<outstr<<endl;
    return 0;
}

程序的实现原理是:

1. 将字符串转化为对应的十进制数。因为2个十六进制数可以表示一个ASCII码值,所以要提取连续的两个十六进制数,并把它转化为对应的十进制数。

2. char类型和int类型可以相互转换。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值