is there is any fun in the c++ library that takes a dec and return hex

Dani AI

Generated

Brief summary and practical suggestions tied to the earlier replies: is right that the C sprintf family will do the job, and / correctly point out the C++ hex manipulator. For idiomatic C++ there are two common patterns: (A) iostream manipulators with a stringstream to get a hex string, and (B) the modern, allocation-free std::to_chars from <charconv> (C++17). Examples and a few gotchas follow.

#include <sstream>
#include <iomanip>
#include <cstdint>

std::uint32_t value = 305441741;         // decimal input
std::ostringstream oss;
oss << std::hex << std::setw(8) << std::setfill('0') << std::nouppercase << value;
std::string hexStr = oss.str();          // "1234abcd"
#include <charconv>
#include <string>
#include <cstdint>

std::uint32_t value = 305441741;
char buf[32];
auto res = std::to_chars(buf, buf + sizeof(buf), value, 16);
std::string hexStr(buf, res.ptr);        // "1234abcd"

Notes and troubleshooting (complements to the thread): casting matters — cast signed integers to an unsigned type to see the full bit-pattern instead of a leading minus; std::hex is sticky on a stream (restore with std::dec); std::showbase will add the 0x prefix and std::uppercase makes A–F uppercase (streams only); std::to_chars is fastest and locale-independent but requires C++17 and produces lowercase hex by default. The stringstream approach is portable across older compilers and is simple when formatting (width, fill, prefix) is required.

Recommended Answers

All 6 Replies

sprintf() will do it -- the format string is "%x" or "%X"

that's c not c++
do u know anyother sol. in c++

I would think sprintf() is as much C++ as null terminated char arrays are. However, if you don't like using C style I/O and all you want to do is to see the hex equivalent of a value, not manipulate the hex equivalent of a value, then there is a stream flag/modifier by the name of hex that can be used to view the value of a numeric variable as hex as opposed to dec.

>that's c not c++
sprintf is C++ too.

>do u know anyother sol. in c++
Yes, use the hex manipulator with either cout or a string stream. Alternatively, you can do the conversion manually, but since that's available in C as well, I guess it doesn't count as C++. :icon_rolleyes:

if you can send an example please, how can i write it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.