本程序实现的功能是将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类型可以相互转换。