Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format hex numbers using stringstream

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?

like image 325
mtijn Avatar asked Aug 05 '14 15:08

mtijn


People also ask

How do you write hex numbers in C++?

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.

What is STD hex?

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)

How do you read hexadecimal in CPP?

#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)]; } …

What is C++ Stringstream?

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.


1 Answers

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

like image 191
Praetorian Avatar answered Sep 23 '22 09:09

Praetorian