Page Menu
Home
Phabricator
Search
Configure Global Search
Log In
Paste
P55
OTBS Sample
Active
Public
Actions
Authored by
jcmcdonald
on Mar 27 2020, 1:11 PM.
Edit Paste
Archive Paste
View Raw File
Subscribe
Mute Notifications
Award Token
Tags
Programming [Dept]
Standards Board [Access]
Subscribers
None
/* Convert an integer to a string
* \param the integer to convert
* \param the base for the conversion, default base10
* \param letter case to use for digits greater than 9
* \param the notation to use for nondecimal bases.
* \return the string representing the value.
*/
template
<
typename
T
>
std
::
string
stringify_integral
(
const
T
&
val
,
const
IOFormatBase
&
base
=
IOFormatBase
::
dec
,
const
IOFormatSign
&
sign
=
IOFormatSign
::
automatic
,
const
IOFormatNumCase
&
num_case
=
IOFormatNumCase
::
upper
,
const
IOFormatBaseNotation
&
notation
=
IOFormatBaseNotation
::
prefix
)
{
/* IMPLEMENTATION MEMO: itos() is not portable, and std::to_string()
does not support multiple bases at this time. Therefore, a custom
solution is called for. */
// If the number is zero, skip everything else and return that.
if
(
val
==
0
)
{
return
"0"
;
}
unsigned
int
_base
=
static_cast
<
unsigned
int
>
(
base
);
/* Create a new string with a reserved length matching the expected
* length of the string. */
std
::
string
str
=
std
::
string
();
str
.
reserve
(
lengthify_integral
(
val
,
base
,
sign
));
bool
prefix
=
false
;
if
(
notation
==
IOFormatBaseNotation
::
prefix
&&
(
_base
==
2

_base
==
3

_base
==
8

_base
==
12

_base
==
16
))
{
prefix
=
true
;
}
else
if
(
_base
!=
10
&&
notation
!=
IOFormatBaseNotation
::
none
)
{
str
+=
DIGIT_CHARS_LOWER
[
_base
%
10
];
if
(
_base
>
10
)
{
str
+=
DIGIT_CHARS_LOWER
[
_base
/
10
];
}
str
+=
'_'
;
}
/* Make a copy of the number for mutating.
* If it's negative, make it positive. */
T
number
=
(
val
>=
0
)
?
val
:

val
;
while
(
number
)
{
size_t
digit
=
number
%
_base
;
switch
(
num_case
)
{
case
IOFormatNumCase
::
lower
:
str
+=
DIGIT_CHARS_LOWER
[
digit
];
break
;
case
IOFormatNumCase
::
upper
:
str
+=
DIGIT_CHARS_UPPER
[
digit
];
break
;
}
number
/=
_base
;
}
if
(
prefix
)
{
switch
(
_base
)
{
case
2
:
str
+=
'b'
;
break
;
case
3
:
str
+=
't'
;
break
;
case
8
:
str
+=
'o'
;
break
;
case
12
:
str
+=
'z'
;
break
;
case
16
:
str
+=
'x'
;
break
;
}
str
+=
'0'
;
}
if
(
val
<
0
)
{
str
+=
""
;
}
else
if
(
sign
==
IOFormatSign
::
always
)
{
str
+=
"+"
;
}
return
reverse
(
str
);
}
std
::
string
stringify_char
(
const
char
&
val
,
const
IOFormatCharValue
&
as
=
IOFormatCharValue
::
as_char
)
{
switch
(
as
)
{
case
IOFormatCharValue
::
as_char
:
return
std
::
string
(
1
,
val
);
case
IOFormatCharValue
::
as_int
:
return
stringify_integral
(
val
,
IOFormatBase
::
dec
);
}
return
""
;
}
Event Timeline
jcmcdonald
created this paste.
Mar 27 2020, 1:11 PM
20200327 13:11:55 (UTC7)
jcmcdonald
mentioned this in
Unknown Object (Slowvote Poll)
.
Log In to Comment