2

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.

Koz Ross
  • 3,040
  • 2
  • 24
  • 44

1 Answers1

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