Is there any biult-in function to convert from hex to chararray
I am new user to C++ and would like to know if there is any biult-in function to convert from hex to chararray?
Regards
Define "hex".
Are you talking about a hex string such as "0x5bac", a hex string such as "5bac", a hex number such os 0x5bac?
You can use these functions. I wrote them with the Qt QChar and QString classes and haven't tested them with the std:: containers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
unsigned int ToNum(char in)
{
int out = in;
if (out >= 'A' && out <= 'F')
out -= ('A' - 10);
else if (out >= 'a' && out <= 'f')
out -= ('a' - 10);
else
out -= '0';
return out;
}
unsigned int str2num(std::string num, int base)
{
unsigned int output = 0;
for (int i = 0; i < num.length(); ++i)
{
output *= base;
output += ToNum(num.at(i));
}
return output;
}
unsigned int str2dec( std::string str)
{
return str2num(str, 10);
}
unsigned int str2hex( std::string str)
{
if (str.length() > 2)
if (str.at(0) == '0' && (str.at(1) == 'x' || str.at(1) == 'X'))
str.erase(0,2);
return str2num(str, 16);
}
unsigned int str2bin( std::string str)
{
return str2num(str, 2);
}
double str2doub(std::string str)
{
std::stringstream iss(str);
double out;
iss >> out;
return out;
}
|
You would use it like:
std::cout << str2num(0x5bac, 8);
Last edited on
It is not clear what you want. Do you want to convert an integer to a string in hex format? In that case you can use std::ostringstream.
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
int main()
{
int n = 0x80;
std::ostringstream oss;
oss << std::hex << n;
std::string str = oss.str();
}
|
Topic archived. No new replies allowed.