0

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[])
{
    if(argc=3)
    {    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; }

Edited by ccbuilder

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by ccbuilder
0

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.

0

could you show an example

Is there a way of doing it wit atoi()

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.