Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ easy way to convert int to string with unknown base

Here is code in Java:

int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);

Now I want the same in C++, but all the conversions i find convert to base 10 only. I ofc dont want to implement this by mysleft, why to write something what already exists

like image 890
kajacx Avatar asked Aug 31 '25 21:08

kajacx


2 Answers

although std::strtol is more flexible, in a controlled case you can use itoa as well.

int a = 456;
int b = 5;
char buffer[32];
itoa(a, buffer, b);
like image 146
yildirim Avatar answered Sep 03 '25 11:09

yildirim


If you want base 8 or 16 you can easily use the string manipulators std::oct and std::hex. If you want arbitrary bases, I suggest checking out this question.

like image 20
KitsuneYMG Avatar answered Sep 03 '25 10:09

KitsuneYMG