1

C++11/14/17 provides functions from string to int/long, but what about vice versa?

I wish to convert an integer to a binary string and then prints it, like:

int i = 127;
char buf[20];
ltoa(i, buf, 2);
printf("%032s\n", buf);

I can see

00000000000000000000000001111111

Currently I could only use C style function on different platforms, like on linux I've ltoa, on windows, _itoa_s (cannot be more ugly) ...

But what about c++?

Thanks a lot.

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • `itoa()` and `ltoa()` are not part of standard C either. In C, you will use functions like `sscanf()`. In C++, you can use an string stream (`std::istringstream`). – Peter Sep 07 '19 at 07:42
  • Possible duplicate of [How to print (using cout) a number in binary form?](https://stackoverflow.com/questions/7349689/how-to-print-using-cout-a-number-in-binary-form) `std::bitset` – David C. Rankin Sep 07 '19 at 08:15

1 Answers1

2

In C++17, we have to_chars:

int i = 127;
char buf[20];
auto [p, e] = std::to_chars(buf, buf + 20, i, 2);

The first two parameters are of type char* and denote the buffer. The third parameter is the number. The last parameter is the base. This is essentially the same with ltoa.

p is the past-the-end pointer. e is the error code. Note that the string is not null-terminated.

(live demo)

L. F.
  • 19,445
  • 8
  • 48
  • 82