Is there a Phobos function that converts an unsigned integer to a binary string? I've searched, but couldn't find one - just want to make sure I'm not reinventing the wheel by writing my own.
Asked
Active
Viewed 66 times
2
-
Please clarify what you mean by converting an integer to a binary string. Are you looking to convert `22` to `"22"`, or do you mean some other type of conversion? – Jonathan M Davis Oct 09 '14 at 06:45
-
I'm looking to convert ``13`` to ``"1101"``, actually. – Koz Ross Oct 09 '14 at 06:46
-
1So, you want to convert an integer to a base 2 value as a string? – Jonathan M Davis Oct 09 '14 at 06:47
1 Answers
5
std.conv.to
is the swiss army knife of conversion functions, and it supports converting to and from different bases. So, if you want to convert 13 to its base 2 value as a string - "1101"
- then you'd do
auto str = to!string(13, 2);
assert(str == "1101");
and to convert a string containing a base 2 integer to an integer, just do the reverse
auto i = to!int("1101", 2);
assert(i == 13);
std.conv.parse
has similar functionality, but it's for parsing a value from the beginning of a string (with the idea of parsing out several whitespace-separated values from the string) rather than converting the entire string at once. It also doesn't work to construct a string from a value, just a value from a string.

Jonathan M Davis
- 37,181
- 17
- 72
- 102