c++ std::cout in hexadecimal
You need to cast it to an `int:
char c = 15;
cout << hex << setfill('0') << setw(2) << static_cast<int>(c); // prints "0f"
hex
only affects integer I/O, which char
isn't considered part of - so your code ends up still outputting the actual char
s.
Note that if char
is signed and you need this to work on values larger than 0x7f
, you will have to cast it first to unsigned char
and then to unsigned int
:
cout << hex << setfill('0') << setw(2)
<< static_cast<unsigned int>(static_cast<unsigned char>(c));
cout print hex instead of decimal
You probably have set std::cout to print hex in prior in the context of your code but forget to reset. For example:
std::cout<<std::hex<<12;
/*blah blah blah*/
std::cout<<12; //this will print in hex form still
so you have to do like the following
std::cout<<std::dec<<12;
to print in decimal form.
How can I print 0x0a instead of 0xa using cout?
This works for me in GCC:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "0x" << setfill('0') << setw(2) << right << hex << 10 << endl;
}
If you are getting sick and tired of iostream's formatting quirkiness, give Boost.Format a try. It allows good-old-fashioned, printf-style format specifiers, yet it is type-safe.
#include <iostream>
#include <boost/format.hpp>
int main()
{
std::cout << boost::format("0x%02x\n") % 10;
}
UPDATE (2019)
Check out the {fmt} library that's been accepted into C++20. Benchmarks show it to be faster than Boost.Format.
#if __has_include(<format>)
#include <format>
using std::format;
#else
#include <fmt/format.h>
using fmt::format;
#endif
std::cout << format("{:#04x}\n", 10);
cout' displays integer as hex
That's because you changed the base of the output in the following line:
out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;
The std::hex
in the end of the line will apply to every subsequent input stream to out
.
Change it back to decimal before printing the last line:
out << " ---> " << std::dec << result << '\n';
Strange output when printing char assigned to hex value using std::cout
Most likely you expect data1 and data3 to be printed as some kind of numbers. However, the data type is character, which is why C++ (or C) would interpret them as characters, mapping 0x11 to the corresponding ASCII character (a control character), similar for 0x22 except some other character (see an ASCII table).
If you want to print those characters as number, you need to convert them to int
prior to printing them out like so (works for C and C++):
cout << (int)data1 << endl;
Or more C++ style would be:
cout << static_cast<int>(data1) << endl;
If you want to display the numbers in hexadecimal, you need to change the default output base using the hex
IO manipulator. Afterwards all output is done in hexadecimal. If you want to switch back to decimal output, use dec
. See cppreference.com for details.
cout << hex << static_cast<int>(data1) << endl;
How to plus hex( No output)?
What I understand is that you want to retrieve the result in an hexadecimal specific format XXXX
.
Computing the addition is the same as any number base, you only need to use (here I display) the result in your format.
You can do this, for instance:
#include <iostream>
#include <iomanip>
std::string displayInPersonalizedHexa(unsigned int a)
{
std::stringstream ss;
ss << std::uppercase<< std::setfill('0') << std::setw(4) << std::hex<< a;
std::string x;
ss >>x;
//std::cout << x;
return x;
}
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
// displays 000B
std::cout << displayInPersonalizedHexa(c) << std::endl;
// adds c=c+1
c=c+1;
// displays 000C
std::cout << displayInPersonalizedHexa(c) << std::endl;
//0xC+5 = 0x11
c=c+5;
// displays 0011
std::cout << displayInPersonalizedHexa(c) << std::endl;
}
This will output
000B
000C
0011
How do you convert a `std::string` hex value to an `unsigned char`
As a very simple solution, you can use a istringstream
, which allows parsing hex strings:
#include <cstdio>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::vector<unsigned char> cipher_as_chars(std::string const& cipher) {
std::istringstream strm{cipher};
strm >> std::hex;
return {std::istream_iterator<int>{strm}, {}};
}
int main() {
auto const cipher = "a8 49 7f ac 24 77 c3 6e 70 ca 99 ca fc e2 c5 7b";
auto const sep = cipher_as_chars(cipher);
for (auto elm : sep) {
std::printf("%hhx ", elm);
}
std::putchar('\n');
}
Related Topics
Where to Put Default Parameter Value in C++
Initialize a Const Array in a Class Initializer in C++
The Differences Between Initialize, Define, Declare a Variable
A Most Vexing Parse Error: Constructor With No Arguments
Are Variable Length Arrays There in C++
How to Parse a Url in C++ Cross Platform
_Builtin_Prefetch, How Much Does It Read
Pinpointing "Conditional Jump or Move Depends on Uninitialized Value(S)" Valgrind Message
How to Get the Argument Types of a Function Pointer in a Variadic Template Class
Determine the Size of a C++ Array Programmatically
Determining 32 VS 64 Bit in C++
Will New Return Null in Any Case
Why Are Two Different Concepts Both Called "Heap"
Requesting Administrator Privileges At Run Time
Same Random Numbers Every Loop Iteration
What's the Right Way to Overload Operator== for a Class Hierarchy