Question: I have a function that should take as parameter an unsigned long long in the hex format. I am trying to convert this parameter to a string to check if it is made of 16 digits or not, but I am having problems with leading zeros

```
template <typename T>
static string to_string(const T& value) {
stringstream oss;
oss << hex << setprecision(16) << value;
return oss.str();
}

int main(int argc, char** argv) {

    unsigned long long pattern1 = 0x0000001000000002;
    unsigned long long pattern2 = 0x0FFFFFFFFFFFFFFFF;

    cout << "Pattern 1 = " << to_string(pattern1) << endl;
    cout << "Pattern 2 = " << to_string(pattern2) << endl;

    return 0;
}

```

What I want is for the pattern 1 to be converted with the zeroes to be able to check its length but this is the output. I tried using the set precision but didn't seem to help

```
Pattern 1 = 1000000002
Pattern 2 = ffffffffffffffff

```

Answer: 
You cannot know the number of the digits that was *"entered by the user"* except if you already read it through an "array" (`char*`, `std::string`, ...).

If you have an `unsigned long long`, the variable size will be `8` bytes anyway:

```
unsigned long long a = 0x1; // This will internally be: 0x0000000000000001

```

---

Now, if you want to get back the leading zeros from the actual type in the `std::string`, I think the following should do the trick (as already mentioned by other answers):

```
template <typename T>
std::string to_string(const T & val)
{
    std::stringstream oss;
    oss << std::hex << std::setfill('0') << std::setw(sizeof(T)*2) << val;
    return oss.str();
}

```

But perhaps it could be better to overload the function for any integral types you want to use instead of using a `template`.  

Because if someone calls the function with a type that is not a `short`, `int`, `long`, `long long` (resp. `unsigned`), the function will be broken.
The length of an `unsigned long long` represented as an hexadecimal number, including leading zeros, is:

```
sizeof(unsigned long long)*2

```

Since we are including leading zeros, the value of the `unsigned long long` is not relevant.