What is the easiest / most elegant way to calculate the length of a number written as text?

Given the maximum possible value, is it simple to express the space needed to write such a number in decimal form as text?

The real challenge: pid_tfixed-length registration process identifiers ( ) using gcc on Linux. It would be nice if the compilation time expression is used in iomanipulator std::setw().

I found that the linux / threads.h header contains a value PID_MAXwith the maximum pid value allocated for the process. So having

#define LENGTH(t) sizeof(#t)-1

LENGTH(PID_MAX) will be an expression of compilation time, but unfortunately this number is defined in hexa:

#define PID_MAX 0x8000

My best best solution is a little weird

static_cast<int>( ::floor( ::log(PID_MAX)/::log(10) + 1 ) );

But this is the computed runtime and uses the functions from math.h

+3
2

- :

//NunLength_interal does the actual calculation. 
template <unsigned num>
struct NumLength_internal
{ enum { value = 1 + NumLength_internal<num/10>::value }; };

template <>
struct NumLength_internal<0>
{ enum { value = 0 }; };

//NumLength is a wrapper to handle zero. For zero we want to return
//a length of one as a special case.
template <unsigned num>
struct NumLength
{ enum { value = NumLength_internal<num>::value };};

template <>
struct NumLength<0>
{ enum { value = 1 }; };

. :

cout << NumLength<0>::value      << endl; // writes: 1
cout << NumLength<5>::value      << endl; // writes: 1
cout << NumLength<10>::value     << endl; // writes: 2
cout << NumLength<123>::value    << endl; // writes: 3
cout << NumLength<0x8000>::value << endl; // writes: 5

.

: , , , , .

+14

, , , :

CHAR_BIT * sizeof(PID_MAX) , PID_MAX. (10) = 3.32 3. , .

#define LENGTH(t) (((CHAR_BIT * sizeof(t)) / 3) + 1)

, t .

+2

Source: https://habr.com/ru/post/1714862/


All Articles