How to boost::any_cast into std::string - c++

I have this test snippet
#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <bitset>
#include <string>
class wrapper {
int value;
char character;
std::string str;
public:
wrapper(int i, char c, std::string s) {
value = i;
character = c;
str = s;
}
void get_data(){
std::cout << "Value = " << value << std::endl;
std::cout << "Character = " << character << std::endl;
std::cout << "String= " << str << std::endl;
}
};
int main(){
std::vector<boost::any> container;
container.push_back(10);
container.push_back(1.4);
container.push_back("Mayukh");
container.push_back('A');
container.push_back(std::bitset<16>(255) );
wrapper wrap(20, 'M', "Alisha");
container.push_back(wrap);
std::cout << boost::any_cast<int>(container[0]) << std::endl;
std::cout << boost::any_cast<double>(container[1]) << std::endl;
std::cout << boost::any_cast<std::string>(container[2]);
std::cout << boost::any_cast<char>(container[3]) << std::endl;
std::cout << boost::any_cast<std::bitset<16>>(container[4]);
auto p = boost::any_cast<wrapper>(container[5]);
p.get_data();
return 0;
}
In this boost::any_cast gives bad_casting exception for std::string. It means for some reason it is not able to typecast boost::any into std::string. While other classes like bitset or my own user defined class is working. Can you please tell me why & a way out of this?

"Mayukh" is not a std::string, it is a const array of 7 characters {'M', 'a', 'y', 'u', 'k', 'h', '\0'}. In C++14, "Mayukh"s is a std::string after using namespace std::literals::string_literals;.
In C++11, std::string("Mayukh") is a std::string as well.
boost::any only supports converting back to the exact same type (well, up to some decay/const/etc). It does not support conversions between the types. See boost any documentation:
Discriminated types that contain values of different types but do not attempt conversion between them, i.e. 5 is held strictly as an int and is not implicitly convertible either to "5" or to 5.0. Their indifference to interpretation but awareness of type effectively makes them safe, generic containers of single values, with no scope for surprises from ambiguous conversions.
Augmenting any with extra smart conversions can be done. For example, a pseudo-any that takes an incoming type, and possibly auto-converts it (so it won't store shorts: it converts all signed integral types to int64_t and unsigned to uint64_t, it converts "hello" to std::string("hello"), etc) before storing it.

That's because "Mayukh" is not a std::string. It's a const char[7], which would decay into const char*:
boost::any a = "Mayukh";
std::cout << a.type().name() << '\n'; // prints PKc, pointer to const char
if (boost::any_cast<const char*>(&a)) {
std::cout << "yay\n"; // prints yay
}
If you want to be able to use any_cast<std::string>, you'd need to put it in as a std::string:
container.push_back(std::string("Mayukh"));

This is not an answer to the question body but rather to the title to help others who also come here from google:
bool is_char_ptr(const boost::any & operand)
{
try {
boost::any_cast<char *>(operand);
return true;
}
catch (const boost::bad_any_cast &) {
return false;
}
}
std::string any2string(boost::any anything)
{
if (anything.type() == typeid(int)) {
return std::to_string( boost::any_cast<int>(anything) );
}
if (anything.type() == typeid(double)) {
return std::to_string(boost::any_cast<double>(anything));
}
if (is_char_ptr(anything)) {
return std::string(boost::any_cast<char *>(anything));
}
if (boost::any_cast<std::string>(anything)) {
return boost::any_cast<std::string>(anything);
}
}
The last if looks weird but it works because the function is overloaded.

Related

Why does the equal function return true when comparing vectors of C-style strings? [duplicate]

This question already has answers here:
comparison between string literal
(4 answers)
Comparison with string literal results in unspecified behaviour?
(4 answers)
Closed 14 days ago.
Please explain why in some cases it is true and in other cases it is false, although in all three cases the addresses of the strings are different?
In the first case, vectors are simply initialized with string literals and then iterators of those strings are passed to the equal function.
The result is true.
Since C-style strings have no comparison operators, their addresses are compared, but when the addresses of strings in vectors are output, it shows that the addresses are not equal. Why then does the result of the equal function get true?
In the second case, vectors are already initialized from pointers to C-style strings. In this case true is also returned, though again the string addresses are different. Why?
In the third case, vectors are initialized using two-dimensional arrays. In this case, again, the addresses of strings in vectors are different, but this time the output is false
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main()
{
std::cout << std::boolalpha;
std::vector<const char*> vec_e{ "String" };
std::vector<const char*> vec_f{ "String" };
std::cout << equal(vec_e.begin(), vec_e.end(), vec_f.begin()) << std::endl; // true
std::cout << &vec_e[0] << std::endl;
std::cout << &vec_f[0] << std::endl;
const char* str_a[1] = { "Hello" };
const char* str_b[1] = { "Hello" };
std::vector<const char*> vec_a(std::begin(str_a), std::end(str_a));
std::vector<const char*> vec_b(std::begin(str_b), std::end(str_b));
std::cout << equal(vec_a.begin(), vec_a.end(), vec_b.begin()) << std::endl; // true
std::cout << &vec_a[0] << std::endl;
std::cout << &vec_b[0] << std::endl;
const char str_c[][6] = { "World" };
const char str_d[][6] = { "World" };
std::vector<const char*> vec_c(std::begin(str_c), std::end(str_c));
std::vector<const char*> vec_d(std::begin(str_d), std::end(str_d));
std::cout << equal(vec_c.begin(), vec_c.end(), vec_d.begin()) << std::endl; // false
std::cout << &vec_c[0] << std::endl;
std::cout << &vec_d[0] << std::endl;
return 0;
}
All 3 compare the addresses, not the strings. The first 2 compare the addresses of string literals, which can be the same when the strings are equal.
The first 2 examples can be rewritten as:
const char *a = "Hello";
const char *b = "Hello";
cout << (a == b);
It is implementation defined if a and b point to the same address or if the compiler uses 2 separate string literals.
The third one is:
const char a[] = "Hello";
const char b[] = "Hello";
cout << (a == b);
where the arrays obviously don't have the same address.
The &vec_e[0] are wrong in the std::cout, they should be (void*)vec_e[0], then it will tell you the addresses, which are compared. The cast is necessary, otherwise it would print the string, not the address.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main()
{
std::cout << std::boolalpha;
std::vector<const char*> vec_e{ "String" };
std::vector<const char*> vec_f{ "String" };
std::cout << equal(vec_e.begin(), vec_e.end(), vec_f.begin()) << std::endl; // true
std::cout << (void*)vec_e[0] << std::endl;
std::cout << (void*)vec_f[0] << std::endl;
const char* str_a[6] = { "Hello" };
const char* str_b[6] = { "Hello" };
std::vector<const char*> vec_a(std::begin(str_a), std::end(str_a));
std::vector<const char*> vec_b(std::begin(str_b), std::end(str_b));
std::cout << equal(vec_a.begin(), vec_a.end(), vec_b.begin()) << std::endl; // true
std::cout << (void*)vec_a[0] << std::endl;
std::cout << (void*)vec_b[0] << std::endl;
const char str_c[][6] = { "World" };
const char str_d[][6] = { "World" };
std::vector<const char*> vec_c(std::begin(str_c), std::end(str_c));
std::vector<const char*> vec_d(std::begin(str_d), std::end(str_d));
std::cout << equal(vec_c.begin(), vec_c.end(), vec_d.begin()) << std::endl; // false
std::cout << (void*)vec_c[0] << std::endl;
std::cout << (void*)vec_d[0] << std::endl;
return 0;
}
will print
true
0x4030a0
0x4030a0
true
0x4030e0
0x4030e0
false
0x7fffd05dcb70
0x7fffd05dcb90

Hexadecimal representation of an integer to std::string [duplicate]

How do I convert an integer to a hex string in C++?
I can find some ways to do it, but they mostly seem targeted towards C. It doesn't seem there's a native way to do it in C++. It is a pretty simple problem though; I've got an int which I'd like to convert to a hex string for later printing.
Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first << with << "0x" or whatever you like if you wish.
Other manips of interest are std::oct (octal) and std::dec (back to decimal).
One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
So finally, I'd suggest such a function:
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
To make it lighter and faster I suggest to use direct filling of a string.
template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I)<<1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len,'0');
for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
rc[i] = digits[(w>>j) & 0x0f];
return rc;
}
You can do it with C++20 std::format:
std::string s = std::format("{:x}", 42); // s == 2a
Until std::format is widely available you can use the {fmt} library, std::format is based on (godbolt):
std::string s = fmt::format("{:x}", 42); // s == 2a
Disclaimer: I'm the author of {fmt} and C++20 std::format.
Use std::stringstream to convert integers into strings and its special manipulators to set the base. For example like that:
std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();
Just print it as an hexadecimal number:
int i = /* ... */;
std::cout << std::hex << i;
#include <boost/format.hpp>
...
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
You can try the following. It's working...
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
ostringstream oss;
oss << f << t;
return oss.str();
}
int main ()
{
cout<<to_string<long>(123456, hex)<<endl;
system("PAUSE");
return 0;
}
Since C++20, with std::format, you might do:
std::format("{:#x}", your_int); // 0x2a
std::format("{:#010x}", your_int); // 0x0000002a
Demo
Just have a look on my solution,[1] that I verbatim[2] copied from my project. My goal was to combine flexibility and safety within my actual needs:[3]
no 0x prefix added: caller may decide
automatic width deduction: less typing
explicit width control: widening for formatting, (lossless) shrinking to save space
capable for dealing with long long
restricted to integral types: avoid surprises by silent conversions
ease of understanding
no hard-coded limit
#include <string>
#include <sstream>
#include <iomanip>
/// Convert integer value `val` to text in hexadecimal format.
/// The minimum width is padded with leading zeros; if not
/// specified, this `width` is derived from the type of the
/// argument. Function suitable from char to long long.
/// Pointers, floating point values, etc. are not supported;
/// passing them will result in an (intentional!) compiler error.
/// Basics from: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
return ss.str();
}
[1] based on the answer by Kornel Kisielewicz
[2] Only the German API doc was translated to English.
[3] Translated into the language of CppTest, this is how it reads:
TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
// width deduction test as suggested by Lightness Races in Orbit:
TEST_ASSERT(int_to_hex(short(0x12)) == "0012");
Thanks to Lincoln's comment below, I've changed this answer.
The following answer properly handles 8-bit ints at compile time. It doees, however, require C++17. If you don't have C++17, you'll have to do something else (e.g. provide overloads of this function, one for uint8_t and one for int8_t, or use something besides "if constexpr", maybe enable_if).
template< typename T >
std::string int_to_hex( T i )
{
// Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");
std::stringstream stream;
stream << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2) << std::hex;
// If T is an 8-bit integer type (e.g. uint8_t or int8_t) it will be
// treated as an ASCII code, giving the wrong result. So we use C++17's
// "if constexpr" to have the compiler decides at compile-time if it's
// converting an 8-bit int or not.
if constexpr (std::is_same_v<std::uint8_t, T>)
{
// Unsigned 8-bit unsigned int type. Cast to int (thanks Lincoln) to
// avoid ASCII code interpretation of the int. The number of hex digits
// in the returned string will still be two, which is correct for 8 bits,
// because of the 'sizeof(T)' above.
stream << static_cast<int>(i);
}
else if (std::is_same_v<std::int8_t, T>)
{
// For 8-bit signed int, same as above, except we must first cast to unsigned
// int, because values above 127d (0x7f) in the int will cause further issues.
// if we cast directly to int.
stream << static_cast<int>(static_cast<uint8_t>(i));
}
else
{
// No cast needed for ints wider than 8 bits.
stream << i;
}
return stream.str();
}
Original answer that doesn't handle 8-bit ints correctly as I thought it did:
Kornel Kisielewicz's answer is great. But a slight addition helps catch cases where you're calling this function with template arguments that don't make sense (e.g. float) or that would result in messy compiler errors (e.g. user-defined type).
template< typename T >
std::string int_to_hex( T i )
{
// Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
// Optional: replace above line with this to handle 8-bit integers.
// << std::hex << std::to_string(i);
return stream.str();
}
I've edited this to add a call to std::to_string because 8-bit integer types (e.g. std::uint8_t values passed) to std::stringstream are treated as char, which doesn't give you the result you want. Passing such integers to std::to_string handles them correctly and doesn't hurt things when using other, larger integer types. Of course you may possibly suffer a slight performance hit in these cases since the std::to_string call is unnecessary.
Note: I would have just added this in a comment to the original answer, but I don't have the rep to comment.
I can see all the elaborate coding samples others have used as answers, but there is nothing wrong with simply having this in a C++ application:
printf ("%04x", num);
for num = 128:
007f
https://en.wikipedia.org/wiki/Printf_format_string
C++ is effectively the original C language which has been extended, so anything in C is also perfectly valid C++.
A new C++17 way: std::to_chars from <charconv> (https://en.cppreference.com/w/cpp/utility/to_chars):
char addressStr[20] = { 0 };
std::to_chars(std::begin(addressStr), std::end(addressStr), address, 16);
return std::string{addressStr};
This is a bit verbose since std::to_chars works with a pre-allocated buffer to avoid dynamic allocations, but this also lets you optimize the code since allocations get very expensive if this is in a hot spot.
For extra optimization, you can omit pre-initializing the buffer and check the return value of to_chars to check for errors and get the length of the data written. Note: to_chars does NOT write a null-terminator!
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
I do:
int hex = 10;
std::string hexstring = stringFormat("%X", hex);
Take a look at SO answer from iFreilicht and the required template header-file from here GIST!
_itoa_s
char buf[_MAX_U64TOSTR_BASE2_COUNT];
_itoa_s(10, buf, _countof(buf), 16);
printf("%s\n", buf); // a
swprintf_s
uint8_t x = 10;
wchar_t buf[_MAX_ITOSTR_BASE16_COUNT];
swprintf_s(buf, L"%02X", x);
My solution. Only integral types are allowed.
You can test/run on https://replit.com/#JomaCorpFX/ToHex
Update. You can set optional prefix 0x in second parameter.
definition.h
#include <iomanip>
#include <sstream>
template <class T, class T2 = typename std::enable_if<std::is_integral<T>::value>::type>
static std::string ToHex(const T & data, bool addPrefix = true);
template<class T, class>
inline std::string ToHex(const T & data, bool addPrefix)
{
std::stringstream sstream;
sstream << std::hex;
std::string ret;
if (typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char) || sizeof(T)==1)
{
sstream << static_cast<int>(data);
ret = sstream.str();
if (ret.length() > 2)
{
ret = ret.substr(ret.length() - 2, 2);
}
}
else
{
sstream << data;
ret = sstream.str();
}
return (addPrefix ? u8"0x" : u8"") + ret;
}
main.cpp
#include <iostream>
#include "definition.h"
int main()
{
std::cout << ToHex<unsigned char>(254) << std::endl;
std::cout << ToHex<char>(-2) << std::endl;
std::cout << ToHex<int>(-2) << std::endl;
std::cout << ToHex<long long>(-2) << std::endl;
std::cout<< std::endl;
std::cout << ToHex<unsigned char>(254, false) << std::endl;
std::cout << ToHex<char>(-2, false) << std::endl;
std::cout << ToHex<int>(-2, false) << std::endl;
std::cout << ToHex<long long>(-2, false) << std::endl;
return 0;
}
Results:
0xfe
0xfe
0xfffffffe
0xfffffffffffffffe
fe
fe
fffffffe
fffffffffffffffe
For those of you who figured out that many/most of the ios::fmtflags don't work with std::stringstream yet like the template idea that Kornel posted way back when, the following works and is relatively clean:
#include <iomanip>
#include <sstream>
template< typename T >
std::string hexify(T i)
{
std::stringbuf buf;
std::ostream os(&buf);
os << "0x" << std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return buf.str().c_str();
}
int someNumber = 314159265;
std::string hexified = hexify< int >(someNumber);
Code for your reference:
#include <iomanip>
#include <sstream>
...
string intToHexString(int intValue) {
string hexStr;
/// integer value to hex-string
std::stringstream sstream;
sstream << "0x"
<< std::setfill ('0') << std::setw(2)
<< std::hex << (int)intValue;
hexStr= sstream.str();
sstream.clear(); //clears out the stream-string
return hexStr;
}
I would like to add an answer to enjoy the beauty of C ++ language. Its adaptability to work at high and low levels. Happy programming.
public:template <class T,class U> U* Int2Hex(T lnumber, U* buffer)
{
const char* ref = "0123456789ABCDEF";
T hNibbles = (lnumber >> 4);
unsigned char* b_lNibbles = (unsigned char*)&lnumber;
unsigned char* b_hNibbles = (unsigned char*)&hNibbles;
U* pointer = buffer + (sizeof(lnumber) << 1);
*pointer = 0;
do {
*--pointer = ref[(*b_lNibbles++) & 0xF];
*--pointer = ref[(*b_hNibbles++) & 0xF];
} while (pointer > buffer);
return buffer;
}
Examples:
char buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns "0000000012345678"
Int2Hex(305419896UL, buffer);//returns "12345678"
Int2Hex((short)65533, buffer);//returns "FFFD"
Int2Hex((char)18, buffer);//returns "12"
wchar_t buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns L"0000000012345678"
Int2Hex(305419896UL, buffer);//returns L"12345678"
Int2Hex((short)65533, buffer);//returns L"FFFD"
Int2Hex((char)18, buffer);//returns L"12"
for fixed number of digits, for instance 2:
static const char* digits = "0123456789ABCDEF";//dec 2 hex digits positional map
char value_hex[3];//2 digits + terminator
value_hex[0] = digits[(int_value >> 4) & 0x0F]; //move of 4 bit, that is an HEX digit, and take 4 lower. for higher digits use multiple of 4
value_hex[1] = digits[int_value & 0x0F]; //no need to move the lower digit
value_hex[2] = '\0'; //terminator
you can also write a for cycle variant to handle variable digits amount
benefits:
speed: it is a minimal bit operation, without external function calls
memory: it use local string, no allocation out of function stack frame, no free of memory needed. Anyway if needed you can use a field or a global to make the value_ex to persists out of the stack frame
ANOTHER SIMPLE APPROACH
#include<iostream>
#include<iomanip> // for setbase(), works for base 8,10 and 16 only
using namespace std;
int main(){
int x = (16*16+16+1)*15;
string ans;
stringstream ss;
ss << setbase(16) << x << endl;
ans = ss.str();
cout << ans << endl;//prints fff
With the variable:
char selA[12];
then:
snprintf(selA, 12, "SELA;0x%X;", 85);
will result in selA containing the string SELA;0x55;
Note that the things surrounding the 55 are just particulars related to the serial protocol used in my application.
#include <iostream>
#include <sstream>
int main()
{
unsigned int i = 4967295; // random number
std::string str1, str2;
unsigned int u1, u2;
std::stringstream ss;
Using void pointer:
// INT to HEX
ss << (void*)i; // <- FULL hex address using void pointer
ss >> str1; // giving address value of one given in decimals.
ss.clear(); // <- Clear bits
// HEX to INT
ss << std::hex << str1; // <- Capitals doesn't matter so no need to do extra here
ss >> u1;
ss.clear();
Adding 0x:
// INT to HEX with 0x
ss << "0x" << (void*)i; // <- Same as above but adding 0x to beginning
ss >> str2;
ss.clear();
// HEX to INT with 0x
ss << std::hex << str2; // <- 0x is also understood so need to do extra here
ss >> u2;
ss.clear();
Outputs:
std::cout << str1 << std::endl; // 004BCB7F
std::cout << u1 << std::endl; // 4967295
std::cout << std::endl;
std::cout << str2 << std::endl; // 0x004BCB7F
std::cout << u2 << std::endl; // 4967295
return 0;
}
char_to_hex returns a string of two characters
const char HEX_MAP[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char replace(unsigned char c)
{
return HEX_MAP[c & 0x0f];
}
std::string char_to_hex(unsigned char c)
{
std::string hex;
// First four bytes
char left = (c >> 4);
// Second four bytes
char right = (c & 0x0f);
hex += replace(left);
hex += replace(right);
return hex;
}
All the answers I read are pretty slow, except one of them, but that one only works for little endian CPUs. Here's a fast implementation that works on big and little endian CPUs.
std::string Hex64(uint64_t number)
{
static const char* maps = "0123456789abcdef";
// if you want more speed, pass a buffer as a function parameter and return an std::string_view (or nothing)
char buffer[17]; // = "0000000000000000"; // uncomment if leading 0s are desired
char* c = buffer + 16;
do
{
*--c = maps[number & 15];
number >>= 4;
}
while (number > 0);
// this strips the leading 0s, if you want to keep them, then return std::string(buffer, 16); and uncomment the "000..." above
return std::string(c, 16 - (c - buffer));
}
Compared to std::format and fmt::format("{:x}", value), I get between 2x (for values > (1ll << 60)) and 6x the speed (for smaller values).
Examples of input/output:
const std::vector<std::tuple<uint64_t, std::string>> vectors = {
{18446744073709551615, "ffffffffffffffff"},
{ 4294967295u, "ffffffff"},
{ 16777215, "ffffff"},
{ 65535, "ffff"},
{ 255, "ff"},
{ 16, "10"},
{ 15, "f"},
{ 0, "0"},
};
You can define MACRO to use as one liner like this.
#include <sstream>
#define to_hex_str(hex_val) (static_cast<std::stringstream const&>(std::stringstream() << "0x" << std::hex << hex_val)).str()
This question is quite old but the answers given are to my opinion not the best.
If you are using C++20 then you have the option to use std::format which is a very good solution. However if you are using C++11/14/17 or below you will not have this option.
Most other answers either use the std::stringstream or implement their own conversion modifying the underlying string buffer directly by themselves.
The first option is rather heavy weight. The second option is inherently insecure and bug prone.
Since I had to implement an integer to hex string lately I chose to do a a true C++ safe implementation using function overloads and template partial specialization to let the compiler handle the type checks. The code uses sprintf (which one of its flavors is generally used by the standard library for std::to_string). And it relies on template partial specialization to correctly select the right sprintf format and leading 0 addition. It separately and correctly handles different pointer sizes and unsigned long sizes for different OSs and architectures. (4/4/4, 4/4/8, 4/8/8)
This answer targets C++11
H File:
#ifndef STRINGUTILS_H_
#define STRINGUTILS_H_
#include <string>
namespace string_utils
{
/* ... Other string utils ... */
std::string hex_string(unsigned char v);
std::string hex_string(unsigned short v);
std::string hex_string(unsigned int v);
std::string hex_string(unsigned long v);
std::string hex_string(unsigned long long v);
std::string hex_string(std::ptrdiff_t v);
} // namespace string_utils
#endif
CPP File
#include "stringutils.h"
#include <cstdio>
namespace
{
template <typename T, int Width> struct LModifier;
template <> struct LModifier<unsigned char, sizeof(unsigned char)>
{
static constexpr char fmt[] = "%02hhX";
};
template <> struct LModifier<unsigned short, sizeof(unsigned short)>
{
static constexpr char fmt[] = "%04hX";
};
template <> struct LModifier<unsigned int, sizeof(unsigned int)>
{
static constexpr char fmt[] = "%08X";
};
template <> struct LModifier<unsigned long, 4>
{
static constexpr char fmt[] = "%08lX";
};
template <> struct LModifier<unsigned long, 8>
{
static constexpr char fmt[] = "%016lX";
};
template <> struct LModifier<unsigned long long, sizeof(unsigned long long)>
{
static constexpr char fmt[] = "%016llX";
};
template <> struct LModifier<std::ptrdiff_t, 4>
{
static constexpr char fmt[] = "%08tX";
};
template <> struct LModifier<std::ptrdiff_t, 8>
{
static constexpr char fmt[] = "%016tX";
};
constexpr char LModifier<unsigned char, sizeof(unsigned char)>::fmt[];
constexpr char LModifier<unsigned short, sizeof(unsigned short)>::fmt[];
constexpr char LModifier<unsigned int, sizeof(unsigned int)>::fmt[];
constexpr char LModifier<unsigned long, sizeof(unsigned long)>::fmt[];
constexpr char LModifier<unsigned long long, sizeof(unsigned long long)>::fmt[];
constexpr char LModifier<std::ptrdiff_t, sizeof(std::ptrdiff_t)>::fmt[];
template <typename T, std::size_t BUF_SIZE = sizeof(T) * 2U> std::string hex_string_(T v)
{
std::string ret(BUF_SIZE + 1, 0);
std::sprintf((char *)ret.data(), LModifier<T, sizeof(T)>::fmt, v);
return ret;
}
} // anonymous namespace
std::string string_utils::hex_string(unsigned char v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned short v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned int v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned long v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned long long v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(std::ptrdiff_t v)
{
return hex_string_(v);
}

Passing C-Style string char * to function argument

I want to change the characters in a string passed by user, converted into a C-style string and passed as an argument to a function with a char * argument:
#include <string>
#include <cstring>
#include <iostream>
#include <stdlib.h>
void functoupper(char *myString)
{
int i=0;
char z;
do {
z= myString[i];
myString[i]=toupper(z);
++i;
} while(myString[i]!=0);
}
int main() {
std::string name;
std::cout << "Please, enter your full name in small caps: ";
std::getline (std::cin,name);
const char *myString = name.c_str();
std::cout << "Hello, " << functoupper(myString) << "!\n";
return 0;
}
I get error error: invalid conversion from 'const char*' to 'char*' [-fpermissive] when calling function functoupper(myString) in main().
The std::string::c_str() method returns a pointer to const char data, but your function expects a pointer to non-const char data. That is why you are getting an error.
You could use const_cast to cast away the const (but that is not really advisable):
char *myString = const_cast<char*>(name.c_str());
functoupper(myString);
std::cout << "Hello, " << name << "!\n";
You could use the non-const std::string::operator[] to access the string's underlying character data (just be careful because prior to C++11, characters were not required to be stored contiguously in memory, but most std::string implementations did):
functoupper(&name[0]);
std::cout << "Hello, " << name << "!\n";
In C++17 and later, you can use the non-const std::string::data() method instead:
functoupper(name.data());
std::cout << "Hello, " << name << "!\n";
That being said, heed this warning when using toupper():
Like all other functions from <cctype>, the behavior of std::toupper is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char ... Similarly, they should not be directly used with standard algorithms when the iterator's value type is char or signed char. Instead, convert the value to unsigned char first
With that said, try something more like this:
#include <string>
#include <iostream>
#include <cctype>
void functoupper(char *myString)
{
for (int i = 0; myString[i] != '\0'; ++i) {
unsigned char z = static_cast<unsigned char>(myString[i]);
myString[i] = static_cast<char>(std::toupper(z));
}
}
int main() {
std::string name;
std::cout << "Please, enter your full name in small caps: ";
std::getline(std::cin, name);
functoupper(&name[0]); // or name.data()
std::cout << "Hello, " << name << "!\n";
return 0;
}
That being said, you should just pass the entire std::string as-is into your function instead, and then you can manipulate it as needed, for instance with the std::transform() algorithm:
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
void functoupper(std::string &myString)
{
std::transform(myString.begin(), myString.end(), myString.begin(),
[](unsigned char ch){ return std::toupper(ch); }
);
}
int main() {
std::string name;
std::cout << "Please, enter your full name in small caps: ";
std::getline(std::cin, name);
functoupper(name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Alternatively:
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
std::string functoupper(std::string myString)
{
std::transform(myString.begin(), myString.end(), myString.begin(),
[](unsigned char ch){ return std::toupper(ch); }
);
return myString;
}
int main() {
std::string name;
std::cout << "Please, enter your full name in small caps: ";
std::getline(std::cin, name);
std::cout << "Hello, " << functoupper(name) << "!\n";
return 0;
}
As #Someprogrammerdude and #RemyLebeau comment, why not simply:
std::transform(std::begin(name), std::end(name), std::begin(name),
[](const unsigned char c)
{
return std::toupper(c);
});
But if you must do it via a char*, then you'll need to copy the data over first, something like:
char myString* = new char[name.size() + 1];
strcpy(myString, name.c_str());
EDIT: Thanks to the helpful comments by #RemyLebeau
Better still avoid all the memory management issues with the above by simply coping your std::string into a std::vector:
std::vector<char> myVec(std::begin(name), std::end(name));
myVec.push_back(`\0`);
and then call your char* function with:
functoupper(myVec.data());

Converting hex number to cstring [duplicate]

How do I convert an integer to a hex string in C++?
I can find some ways to do it, but they mostly seem targeted towards C. It doesn't seem there's a native way to do it in C++. It is a pretty simple problem though; I've got an int which I'd like to convert to a hex string for later printing.
Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first << with << "0x" or whatever you like if you wish.
Other manips of interest are std::oct (octal) and std::dec (back to decimal).
One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
So finally, I'd suggest such a function:
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
To make it lighter and faster I suggest to use direct filling of a string.
template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I)<<1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len,'0');
for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
rc[i] = digits[(w>>j) & 0x0f];
return rc;
}
You can do it with C++20 std::format:
std::string s = std::format("{:x}", 42); // s == 2a
Until std::format is widely available you can use the {fmt} library, std::format is based on (godbolt):
std::string s = fmt::format("{:x}", 42); // s == 2a
Disclaimer: I'm the author of {fmt} and C++20 std::format.
Use std::stringstream to convert integers into strings and its special manipulators to set the base. For example like that:
std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();
Just print it as an hexadecimal number:
int i = /* ... */;
std::cout << std::hex << i;
#include <boost/format.hpp>
...
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
You can try the following. It's working...
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
ostringstream oss;
oss << f << t;
return oss.str();
}
int main ()
{
cout<<to_string<long>(123456, hex)<<endl;
system("PAUSE");
return 0;
}
Since C++20, with std::format, you might do:
std::format("{:#x}", your_int); // 0x2a
std::format("{:#010x}", your_int); // 0x0000002a
Demo
Just have a look on my solution,[1] that I verbatim[2] copied from my project. My goal was to combine flexibility and safety within my actual needs:[3]
no 0x prefix added: caller may decide
automatic width deduction: less typing
explicit width control: widening for formatting, (lossless) shrinking to save space
capable for dealing with long long
restricted to integral types: avoid surprises by silent conversions
ease of understanding
no hard-coded limit
#include <string>
#include <sstream>
#include <iomanip>
/// Convert integer value `val` to text in hexadecimal format.
/// The minimum width is padded with leading zeros; if not
/// specified, this `width` is derived from the type of the
/// argument. Function suitable from char to long long.
/// Pointers, floating point values, etc. are not supported;
/// passing them will result in an (intentional!) compiler error.
/// Basics from: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
return ss.str();
}
[1] based on the answer by Kornel Kisielewicz
[2] Only the German API doc was translated to English.
[3] Translated into the language of CppTest, this is how it reads:
TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
// width deduction test as suggested by Lightness Races in Orbit:
TEST_ASSERT(int_to_hex(short(0x12)) == "0012");
Thanks to Lincoln's comment below, I've changed this answer.
The following answer properly handles 8-bit ints at compile time. It doees, however, require C++17. If you don't have C++17, you'll have to do something else (e.g. provide overloads of this function, one for uint8_t and one for int8_t, or use something besides "if constexpr", maybe enable_if).
template< typename T >
std::string int_to_hex( T i )
{
// Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");
std::stringstream stream;
stream << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2) << std::hex;
// If T is an 8-bit integer type (e.g. uint8_t or int8_t) it will be
// treated as an ASCII code, giving the wrong result. So we use C++17's
// "if constexpr" to have the compiler decides at compile-time if it's
// converting an 8-bit int or not.
if constexpr (std::is_same_v<std::uint8_t, T>)
{
// Unsigned 8-bit unsigned int type. Cast to int (thanks Lincoln) to
// avoid ASCII code interpretation of the int. The number of hex digits
// in the returned string will still be two, which is correct for 8 bits,
// because of the 'sizeof(T)' above.
stream << static_cast<int>(i);
}
else if (std::is_same_v<std::int8_t, T>)
{
// For 8-bit signed int, same as above, except we must first cast to unsigned
// int, because values above 127d (0x7f) in the int will cause further issues.
// if we cast directly to int.
stream << static_cast<int>(static_cast<uint8_t>(i));
}
else
{
// No cast needed for ints wider than 8 bits.
stream << i;
}
return stream.str();
}
Original answer that doesn't handle 8-bit ints correctly as I thought it did:
Kornel Kisielewicz's answer is great. But a slight addition helps catch cases where you're calling this function with template arguments that don't make sense (e.g. float) or that would result in messy compiler errors (e.g. user-defined type).
template< typename T >
std::string int_to_hex( T i )
{
// Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
// Optional: replace above line with this to handle 8-bit integers.
// << std::hex << std::to_string(i);
return stream.str();
}
I've edited this to add a call to std::to_string because 8-bit integer types (e.g. std::uint8_t values passed) to std::stringstream are treated as char, which doesn't give you the result you want. Passing such integers to std::to_string handles them correctly and doesn't hurt things when using other, larger integer types. Of course you may possibly suffer a slight performance hit in these cases since the std::to_string call is unnecessary.
Note: I would have just added this in a comment to the original answer, but I don't have the rep to comment.
I can see all the elaborate coding samples others have used as answers, but there is nothing wrong with simply having this in a C++ application:
printf ("%04x", num);
for num = 128:
007f
https://en.wikipedia.org/wiki/Printf_format_string
C++ is effectively the original C language which has been extended, so anything in C is also perfectly valid C++.
A new C++17 way: std::to_chars from <charconv> (https://en.cppreference.com/w/cpp/utility/to_chars):
char addressStr[20] = { 0 };
std::to_chars(std::begin(addressStr), std::end(addressStr), address, 16);
return std::string{addressStr};
This is a bit verbose since std::to_chars works with a pre-allocated buffer to avoid dynamic allocations, but this also lets you optimize the code since allocations get very expensive if this is in a hot spot.
For extra optimization, you can omit pre-initializing the buffer and check the return value of to_chars to check for errors and get the length of the data written. Note: to_chars does NOT write a null-terminator!
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
I do:
int hex = 10;
std::string hexstring = stringFormat("%X", hex);
Take a look at SO answer from iFreilicht and the required template header-file from here GIST!
_itoa_s
char buf[_MAX_U64TOSTR_BASE2_COUNT];
_itoa_s(10, buf, _countof(buf), 16);
printf("%s\n", buf); // a
swprintf_s
uint8_t x = 10;
wchar_t buf[_MAX_ITOSTR_BASE16_COUNT];
swprintf_s(buf, L"%02X", x);
My solution. Only integral types are allowed.
You can test/run on https://replit.com/#JomaCorpFX/ToHex
Update. You can set optional prefix 0x in second parameter.
definition.h
#include <iomanip>
#include <sstream>
template <class T, class T2 = typename std::enable_if<std::is_integral<T>::value>::type>
static std::string ToHex(const T & data, bool addPrefix = true);
template<class T, class>
inline std::string ToHex(const T & data, bool addPrefix)
{
std::stringstream sstream;
sstream << std::hex;
std::string ret;
if (typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char) || sizeof(T)==1)
{
sstream << static_cast<int>(data);
ret = sstream.str();
if (ret.length() > 2)
{
ret = ret.substr(ret.length() - 2, 2);
}
}
else
{
sstream << data;
ret = sstream.str();
}
return (addPrefix ? u8"0x" : u8"") + ret;
}
main.cpp
#include <iostream>
#include "definition.h"
int main()
{
std::cout << ToHex<unsigned char>(254) << std::endl;
std::cout << ToHex<char>(-2) << std::endl;
std::cout << ToHex<int>(-2) << std::endl;
std::cout << ToHex<long long>(-2) << std::endl;
std::cout<< std::endl;
std::cout << ToHex<unsigned char>(254, false) << std::endl;
std::cout << ToHex<char>(-2, false) << std::endl;
std::cout << ToHex<int>(-2, false) << std::endl;
std::cout << ToHex<long long>(-2, false) << std::endl;
return 0;
}
Results:
0xfe
0xfe
0xfffffffe
0xfffffffffffffffe
fe
fe
fffffffe
fffffffffffffffe
For those of you who figured out that many/most of the ios::fmtflags don't work with std::stringstream yet like the template idea that Kornel posted way back when, the following works and is relatively clean:
#include <iomanip>
#include <sstream>
template< typename T >
std::string hexify(T i)
{
std::stringbuf buf;
std::ostream os(&buf);
os << "0x" << std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return buf.str().c_str();
}
int someNumber = 314159265;
std::string hexified = hexify< int >(someNumber);
Code for your reference:
#include <iomanip>
#include <sstream>
...
string intToHexString(int intValue) {
string hexStr;
/// integer value to hex-string
std::stringstream sstream;
sstream << "0x"
<< std::setfill ('0') << std::setw(2)
<< std::hex << (int)intValue;
hexStr= sstream.str();
sstream.clear(); //clears out the stream-string
return hexStr;
}
I would like to add an answer to enjoy the beauty of C ++ language. Its adaptability to work at high and low levels. Happy programming.
public:template <class T,class U> U* Int2Hex(T lnumber, U* buffer)
{
const char* ref = "0123456789ABCDEF";
T hNibbles = (lnumber >> 4);
unsigned char* b_lNibbles = (unsigned char*)&lnumber;
unsigned char* b_hNibbles = (unsigned char*)&hNibbles;
U* pointer = buffer + (sizeof(lnumber) << 1);
*pointer = 0;
do {
*--pointer = ref[(*b_lNibbles++) & 0xF];
*--pointer = ref[(*b_hNibbles++) & 0xF];
} while (pointer > buffer);
return buffer;
}
Examples:
char buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns "0000000012345678"
Int2Hex(305419896UL, buffer);//returns "12345678"
Int2Hex((short)65533, buffer);//returns "FFFD"
Int2Hex((char)18, buffer);//returns "12"
wchar_t buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns L"0000000012345678"
Int2Hex(305419896UL, buffer);//returns L"12345678"
Int2Hex((short)65533, buffer);//returns L"FFFD"
Int2Hex((char)18, buffer);//returns L"12"
for fixed number of digits, for instance 2:
static const char* digits = "0123456789ABCDEF";//dec 2 hex digits positional map
char value_hex[3];//2 digits + terminator
value_hex[0] = digits[(int_value >> 4) & 0x0F]; //move of 4 bit, that is an HEX digit, and take 4 lower. for higher digits use multiple of 4
value_hex[1] = digits[int_value & 0x0F]; //no need to move the lower digit
value_hex[2] = '\0'; //terminator
you can also write a for cycle variant to handle variable digits amount
benefits:
speed: it is a minimal bit operation, without external function calls
memory: it use local string, no allocation out of function stack frame, no free of memory needed. Anyway if needed you can use a field or a global to make the value_ex to persists out of the stack frame
ANOTHER SIMPLE APPROACH
#include<iostream>
#include<iomanip> // for setbase(), works for base 8,10 and 16 only
using namespace std;
int main(){
int x = (16*16+16+1)*15;
string ans;
stringstream ss;
ss << setbase(16) << x << endl;
ans = ss.str();
cout << ans << endl;//prints fff
With the variable:
char selA[12];
then:
snprintf(selA, 12, "SELA;0x%X;", 85);
will result in selA containing the string SELA;0x55;
Note that the things surrounding the 55 are just particulars related to the serial protocol used in my application.
#include <iostream>
#include <sstream>
int main()
{
unsigned int i = 4967295; // random number
std::string str1, str2;
unsigned int u1, u2;
std::stringstream ss;
Using void pointer:
// INT to HEX
ss << (void*)i; // <- FULL hex address using void pointer
ss >> str1; // giving address value of one given in decimals.
ss.clear(); // <- Clear bits
// HEX to INT
ss << std::hex << str1; // <- Capitals doesn't matter so no need to do extra here
ss >> u1;
ss.clear();
Adding 0x:
// INT to HEX with 0x
ss << "0x" << (void*)i; // <- Same as above but adding 0x to beginning
ss >> str2;
ss.clear();
// HEX to INT with 0x
ss << std::hex << str2; // <- 0x is also understood so need to do extra here
ss >> u2;
ss.clear();
Outputs:
std::cout << str1 << std::endl; // 004BCB7F
std::cout << u1 << std::endl; // 4967295
std::cout << std::endl;
std::cout << str2 << std::endl; // 0x004BCB7F
std::cout << u2 << std::endl; // 4967295
return 0;
}
char_to_hex returns a string of two characters
const char HEX_MAP[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char replace(unsigned char c)
{
return HEX_MAP[c & 0x0f];
}
std::string char_to_hex(unsigned char c)
{
std::string hex;
// First four bytes
char left = (c >> 4);
// Second four bytes
char right = (c & 0x0f);
hex += replace(left);
hex += replace(right);
return hex;
}
All the answers I read are pretty slow, except one of them, but that one only works for little endian CPUs. Here's a fast implementation that works on big and little endian CPUs.
std::string Hex64(uint64_t number)
{
static const char* maps = "0123456789abcdef";
// if you want more speed, pass a buffer as a function parameter and return an std::string_view (or nothing)
char buffer[17]; // = "0000000000000000"; // uncomment if leading 0s are desired
char* c = buffer + 16;
do
{
*--c = maps[number & 15];
number >>= 4;
}
while (number > 0);
// this strips the leading 0s, if you want to keep them, then return std::string(buffer, 16); and uncomment the "000..." above
return std::string(c, 16 - (c - buffer));
}
Compared to std::format and fmt::format("{:x}", value), I get between 2x (for values > (1ll << 60)) and 6x the speed (for smaller values).
Examples of input/output:
const std::vector<std::tuple<uint64_t, std::string>> vectors = {
{18446744073709551615, "ffffffffffffffff"},
{ 4294967295u, "ffffffff"},
{ 16777215, "ffffff"},
{ 65535, "ffff"},
{ 255, "ff"},
{ 16, "10"},
{ 15, "f"},
{ 0, "0"},
};
You can define MACRO to use as one liner like this.
#include <sstream>
#define to_hex_str(hex_val) (static_cast<std::stringstream const&>(std::stringstream() << "0x" << std::hex << hex_val)).str()
This question is quite old but the answers given are to my opinion not the best.
If you are using C++20 then you have the option to use std::format which is a very good solution. However if you are using C++11/14/17 or below you will not have this option.
Most other answers either use the std::stringstream or implement their own conversion modifying the underlying string buffer directly by themselves.
The first option is rather heavy weight. The second option is inherently insecure and bug prone.
Since I had to implement an integer to hex string lately I chose to do a a true C++ safe implementation using function overloads and template partial specialization to let the compiler handle the type checks. The code uses sprintf (which one of its flavors is generally used by the standard library for std::to_string). And it relies on template partial specialization to correctly select the right sprintf format and leading 0 addition. It separately and correctly handles different pointer sizes and unsigned long sizes for different OSs and architectures. (4/4/4, 4/4/8, 4/8/8)
This answer targets C++11
H File:
#ifndef STRINGUTILS_H_
#define STRINGUTILS_H_
#include <string>
namespace string_utils
{
/* ... Other string utils ... */
std::string hex_string(unsigned char v);
std::string hex_string(unsigned short v);
std::string hex_string(unsigned int v);
std::string hex_string(unsigned long v);
std::string hex_string(unsigned long long v);
std::string hex_string(std::ptrdiff_t v);
} // namespace string_utils
#endif
CPP File
#include "stringutils.h"
#include <cstdio>
namespace
{
template <typename T, int Width> struct LModifier;
template <> struct LModifier<unsigned char, sizeof(unsigned char)>
{
static constexpr char fmt[] = "%02hhX";
};
template <> struct LModifier<unsigned short, sizeof(unsigned short)>
{
static constexpr char fmt[] = "%04hX";
};
template <> struct LModifier<unsigned int, sizeof(unsigned int)>
{
static constexpr char fmt[] = "%08X";
};
template <> struct LModifier<unsigned long, 4>
{
static constexpr char fmt[] = "%08lX";
};
template <> struct LModifier<unsigned long, 8>
{
static constexpr char fmt[] = "%016lX";
};
template <> struct LModifier<unsigned long long, sizeof(unsigned long long)>
{
static constexpr char fmt[] = "%016llX";
};
template <> struct LModifier<std::ptrdiff_t, 4>
{
static constexpr char fmt[] = "%08tX";
};
template <> struct LModifier<std::ptrdiff_t, 8>
{
static constexpr char fmt[] = "%016tX";
};
constexpr char LModifier<unsigned char, sizeof(unsigned char)>::fmt[];
constexpr char LModifier<unsigned short, sizeof(unsigned short)>::fmt[];
constexpr char LModifier<unsigned int, sizeof(unsigned int)>::fmt[];
constexpr char LModifier<unsigned long, sizeof(unsigned long)>::fmt[];
constexpr char LModifier<unsigned long long, sizeof(unsigned long long)>::fmt[];
constexpr char LModifier<std::ptrdiff_t, sizeof(std::ptrdiff_t)>::fmt[];
template <typename T, std::size_t BUF_SIZE = sizeof(T) * 2U> std::string hex_string_(T v)
{
std::string ret(BUF_SIZE + 1, 0);
std::sprintf((char *)ret.data(), LModifier<T, sizeof(T)>::fmt, v);
return ret;
}
} // anonymous namespace
std::string string_utils::hex_string(unsigned char v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned short v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned int v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned long v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(unsigned long long v)
{
return hex_string_(v);
}
std::string string_utils::hex_string(std::ptrdiff_t v)
{
return hex_string_(v);
}

Convert a string into a double, and a int. How to?

I'm having trouble converting a string into a double.
My string has been declared using the "string" function, so my string is:
string marks = "";
Now to convert it to a double I found somewhere on the internet to use word.c_str(), and so I did. I called it and used it like this:
doubleMARK = strtod( marks.c_str() );
This is similar to the example I found on the web:
n1=strtod( t1.c_str() );
Apparently, that's how it's done. But of course, it doesn't work. I need another parameter. A pointer I believe? But I'm lost at this point as to what I'm suppose to do. Does it need a place to store the value or something? or what?
I also need to convert this string into a integer which I have not begun researching as to how to do, but once I find out and if I have errors, I will edit this out and post them here.
Was there a reason you're not using std::stod and std::stoi? They are at least 9 levels more powerful than flimsy strtod.
Example
#include <iostream>
#include <string>
int main() {
using namespace std;
string s = "-1";
double d = stod(s);
int i = stoi(s);
cout << s << " " << d << " " << i << endl;
}
Output
-1 -1 -1
If you must use strtod, then just pass NULL as the second parameter. According to cplusplus.com:
If [the second parameter] is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.
And it's not required to be non-NULL.
Back in the Bad Old Dark Days of C, I'd do something ugly and unsafe like this:
char sfloat[] = "1.0";
float x;
sscanf (sfloat, "%lf", &x);
In C++, you might instead do something like this:
// REFERENCE: http://www.codeguru.com/forum/showthread.php?t=231054
include <string>
#include <sstream>
#include <iostream>
template <class T>
bool from_string(T& t,
const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("123.456"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
Personally, though, I'd recommend this:
http://bytes.com/topic/c/answers/137731-convert-string-float
There are two ways. C gives you strtod which converts between a char
array and double:
// C-ish:
input2 = strtod(input.c_str(), NULL);
The C++ streams provide nice conversions to and from a variety of
types. The way to use strings with streams is to use a stringstream:
// C++ streams:
double input2;
istringstream in(input);
input >> input2;
We can define a stringTo() function,
#include <string>
#include <sstream>
template <typename T>
T stringTo(const std::string& s) {
T x;
std::istringstream in(s);
in >> x;
return x;
}
Then, use it like
std::cout << stringTo<double>("-3.1e3") << " " << stringTo<int>("4");