to convert int to hex

Hi,

Can you help me in converting int value to hex in a single command.

Thanks

One way fo doing it is with the printf utility i.e.

printf "%x\n", 123
7b

I am looking for a function/call which does that

printf is a function call.

also sprintf, vsprintf etc.

The thing to remember is that you are not converting the value, but merely displaying it in a different format.

#include <string>
#include <sstream>
using namespace std;

//This spends some extra cycles, offers simplicity, elegance and safety.
string IntToHexString(int i)
{
stringstream ss;
ss<<"0x"<<hex<<i;
string retval; retval=ss.str().c_str();
return retval;
}

//usage
cout<<"Hex for 32 is "<<IntToHexString(32)<<endl;
// as always handle your seh exceptions with a try / catch.

Correct me if I am wrong, but it also either 1) leaks memory, 2) reads a wild pointer, or 3) is thread unsafe:

Logically:

The .c_str call must return a "string".

Given:

A string is a pointer to a "NULL terminated string."

A "NULL terminated string" is a sequence of characters terminated by a '\0' character; we shall call this a "buffer".

A buffer resides somewhere in memory.

Therefore:

The .c_str call must return a pointer a buffer containing its contents.

In order not to leak, the above buffer must be freed at some point. To be freed the buffer must still referenced. Since the caller of IntToHexString does not take a reference then to not leak, either a) someone else must free it or b) someone else has a reference to it.

If (a) then the "somewhere" else may be the destructor of stringstream class. I presume this destructor is called when the stack for your function is cleaned up. This means that the string returned by IntToHexString becomes "wild" as soon as it returns.

If (b) then the buffer can be overwritten at some point by the class still holding a reference to it and therefore can not be thread safe.

If neither a nor b occurs then the code leaks. The only way this is untrue is if the compiler takes care of destroying the string returned by IntToHexString.

#include <stdio.h>
#include <ctype.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    int c, hx;

    hx = 0;
    while ((c = getchar()) != EOF && c != '\n') {
        if (isdigit(c))
            hx = c - '0' + hx * 10;
        else {
            perror(argv[0]);
            return 1;
        }
    }
    printf("%x\n", hx);
    return 0;
}
#include <stdio.h>

int main(int argc, char *argv[])
{
    int c, hx;
    if (argc > 1)
    {
         hx=atol(argv[1]);
    }
    else
    {
         scanf("%d",&hx);
    }
    printf("%x\n", hx);
    return 0;
}