# Decimal to Hex in g++ - UNIX Programming

How do i convert a Decimal number to Hex in g++, I know there is not an itoa function so what is the best way to do this? would it be: char *hexstring[10]; int number = 30; sprintf(hexstring, "%x", number); I will be passing this number to another program which will change the hex to binary. Any help would really be appreciated. Thank You...

1. ## Decimal to Hex in g++

How do i convert a Decimal number to Hex in g++, I know there is not
an itoa function so what is the best way to do this?

would it be:

char *hexstring[10];
int number = 30;
sprintf(hexstring, "%x", number);

I will be passing this number to another program which will change the
hex to binary. Any help would really be appreciated. Thank You
Josh Guest

2. ## Re: Decimal to Hex in g++

Josh Parker <ecu.edu> wrote:

Drop the '*' in front of hexstring, or you get an array of 10
uninitialized char pointers instead of an array with enough space
for 9 characters.

Otherwise that looks completely reasonable, at least as long as you're
on a typical 32-bit machine. To make sure it works with whatever size
an integer has on a machine you could use instead

char hexstring[ ( CHAR_BIT * sizeof( int ) ) / 4 + 2 ];

CHAR_BIT is the number of bits in the smallest unit on your machine
(a char per definitionem), which is typically 8, but could be any
other larger value in principle (don't forget to include <climits>
or <limits.h> when you're using it). The additional 2 is one for
the '\0' at the end of the string and another one for cases where
CHAR_BIT can't be divided by 4.
Regards, Jens
--
\ Jens Thoms Toerring ___ fu-berlin.de
\__________________________ http://www.toerring.de
Jens.Toerring@physik.fu-berlin.de Guest

3. ## Re: Decimal to Hex in g++

fu-berlin.de wrote: [/ref]
[/ref]

One thing I forgot: At least in C (don't know about C++ but I would guess
it's the same) the "%x" is only allowed for _unsigned_ ints.

Regards, Jens
--
\ Jens Thoms Toerring ___ fu-berlin.de
\__________________________ http://www.toerring.de
Jens.Toerring@physik.fu-berlin.de Guest

4. ## Re: Decimal to Hex in g++

fu-berlin.de writes:
[/ref]
> [/ref]
>
> One thing I forgot: At least in C (don't know about C++ but I would guess
> it's the same) the "%x" is only allowed for _unsigned_ ints.
>[/ref]

And better use snprintf() if your system has one instead of sprintf().

Bye, Dragan

--
Dragan Cvetkovic,

To be or not to be is true. G. Boole No it isn't. L. E. J. Brouwer

Dragan Guest

5. ## Re: Decimal to Hex in g++

Josh Parker wrote:

#include <iostream>
#include <sstream>

int main()
{
std::ostringstream ss;

int num = 30;

ss << std::hex << num;

std::cout << ss.str() << "\n";

return 0;
}

Greg Guest

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•