#include <iostream>
#include <sstream>
using namespace std;
int main()
{
/*----------------------------------
十六进制,八进制转十进制
----------------------------------*/
int decimal1,decimal2;
string oct_test = "75";
string hex_test = "A3";
stringstream ss1;
ss1.str(oct_test);
ss1>>oct>>decimal1;
cout<<"Convert oct to decimal:"<<decimal1<<endl;
//ss1.clear();//若不想从新定义stringstream流,必须先清空ss1中的缓存
stringstream ss2;
ss2.str(hex_test);
ss2>>hex>>decimal2;
cout<<"Convert hex to decimal:"<<decimal2<<endl;
/*----------------------------------
十进制转八进制、十六进制
----------------------------------*/
int decimal;
stringstream ss,sss;
cout<<"Enter a decimal number:";
cin>>decimal;
/*下面两句等价于:
cout<<"Convert to hex:"<<hex<<decimal<<endl;
*/
//十进制转十六进制
ss<<hex<<decimal;
cout<<"Convert to hex:"<<ss.str()<<endl;
//十进制转八进制
ss.str(""); //同上,若不想从新定义stringstream流,必须先将ss.str()置为空
ss<<oct<<decimal;
cout<<"Convert to oct:"<<ss.str()<<endl;
system("pause");
return 0;
}
//i要转化的十进制整数,width转化后的宽度,位数不足则补0
std::string dec2hex(int i, int width)
{
std::stringstream ioss; //定义字符串流
std::string s_temp; //存放转化后字符
ioss << std::hex << i; //以十六制形式输出
ioss >> s_temp;
if(width > s_temp.size())
{
std::string s_0(width - s_temp.size(), '0'); //位数不够则补0
s_temp = s_0 + s_temp; //合并
}
std::string s = s_temp.substr(s_temp.length() - width, s_temp.length()); //取右width位
return s;
}
1. 无符号字节数组转16进制字符串
std::string bytesToHexString(const BYTE* bytes,const int length)
{
if (bytes == NULL) {
return "";
}
std::string buff;
const int len = length;
for (int j = 0; j < len; j++) {
/*if ((bytes[j] & 0xff) < 16) {
buff.append("0");
}*/
int high = bytes[j]/16, low = bytes[j]%16;
buff += (high<10) ? ('0' + high) : ('a' + high - 10);
buff += (low<10) ? ('0' + low) : ('a' + low - 10);
}
return buff;
}
2. 16进制字符串 转无符号字节数组
void hexToBytes(const std::string& hex,BYTE* bytes)
{
int bytelen = hex.length() / 2;
std::string strByte;
unsigned int n;
for (int i = 0; i < bytelen; i++)
{
strByte = hex.substr(i * 2, 2);
sscanf(strByte.c_str(),"%x",&n);
bytes[i] = n;
}
}
3. 字符串转16进制字符串
/*
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
std::string encodeHexString(const std::string& str) {
// 根据默认编码获取字节数组
std::string hexString = "0123456789abcdef";
string sb;
// 将字节数组中每个字节拆解成2位16进制整数
for (int i = 0; i < str.length(); i++) {
sb += hexString.at((str[i] & 0xf0) >> 4);
sb += hexString.at((str[i] & 0x0f) >> 0);
}
return sb;
}
4. 16进制字符串转字符串
std::string hexStringToString(const std::string& hexStr)
{
std::string ret;
std::string hexString = "0123456789abcdef";
// 将每2位16进制整数组装成一个字节
for (int i = 0; i < hexStr.length(); i += 2)
ret += BYTE(hexString.find(hexStr.at(i)) << 4 | hexString.find(hexStr.at(i + 1)));
return ret;
}
参考:
- https://www.cnblogs.com/jodio/p/11393177.html
- https://blog.csdn.net/yangzijiangtou/article/details/102827323