Can anyone show or explain how to do a base conversions ? I'm new so this concept is confusing

so far i got to

but I have no clue to get answer from base 10 to any base 2 to base 16

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
    {    int num1 = atoi(argv[1])
        char* bVar = argv[2];
int bVal;
if (bVar[0] == 'b')
    bVal = atoi(bVar + 1);

    if( bVal < 2 || bVal > 16 )
    {cout << "X" << endl; }

Recommended Answers

All 2 Replies

Don't use atoi(). Use strtol(), strtoul(), etc. The last (third) argument passed to the function is the base. It will try to convert intelligently if the base is 0, so if the string is 0xCAFEFACE, it will look at the "0x" and convert from hex, where 01234567 would be treated as octal since it starts with zero and only has digits 0-7. If you pass a second non-null argument (char** endptr) the address of a string pointer, the pointer will be set to where in the passed number string the conversion stopped, such as when it encounters a letter or some other character. Anyway, the signatures are:

long int strtol(const char* nptr, char** endptr, int base);
long long int strtoll(const char* nptr, char** endptr, int base);
unsigned long int strtoul(const char* nptr, char** endptr, int base);
unsigned long long int strtoull(const char* nptr, char** endptr, int base);

Your compiler may or may not support the long long (64-bit values) versions.

could you show an example

Is there a way of doing it wit atoi()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.