I am trying to convert an unsigned short to its hexadecimal representation in uppercase and prefixed with 0's using stringstream. I can't seem to get the uppercase and 0's correct. here is what I have now:
USHORT id = 1127; std::stringstream ss; ss << std::showbase << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << id; std::string result = ss.str();
this results in the prefixed '0x' base also being uppercase but I want that to be lowercase. it also results in no prefixed 0's to the hexadecimal value after the prefixed 0x base (currently 0X). for example, this will now output 0X467 instead of the expected 0x0467. how do I fix this?
Hexadecimal uses the numeric digits 0 through 9 and the letters 'a' through 'f' to represent the numeric values 10 through 15). Each hex digit is directly equivalent to 4 bits. C++ precedes a hexadecimal value that it prints with the characters "0x" to make it clear that the value is in base 16.
std::hex is a special object that, when applied to a stream using operator<< , sets the basefield of the stream str to hex as if by calling str.setf(std::ios_base::hex, std::ios_base::base field)
#include <iostream. h> void main() { int n; while (cin >> n) { cout << "decimal: " << n << endl; //--- Print hex with leading zeros cout << "hex : "; for (int i=2*sizeof(int) - 1; i>=0; i--) { cout << "0123456789ABCDEF"[((n >> i*4) & 0xF)]; } …
The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
setw
is going to set the width of the entire formatted output, including the displayed base, which is why you're not seeing the leading 0
. Also, there's no way to make the base be displayed in lowercase if you use std::showbase
along with std::uppercase
. The solution is to insert the base manually, and then apply the remaining manipulators.
ss << "0x" << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << id;
This outputs 0x0467
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With