Vijay
Vijay

Reputation: 67221

Decimal to hexadecimal conversion: issues with sprintf?

I have a requirement, part of which needs conversion from decimal to hex.

I prefer the following way to do that thing as below:

sprintf(mcc,"%x",n);

n here will be an integer. But my peer says it is not a good way to do that. Instead he says to manually convert the decimal using a function, but I did not get a good explanation about why not to use sprintf.

Are there any problems with the above method I am using?

Should I go for a function which manually converts the decimal number into hex?

Upvotes: 1

Views: 4359

Answers (3)

Kevin
Kevin

Reputation: 56059

The problem with sprintf is that it's hard to guarantee your buffer is big enough. Use snprintf instead.

In this case the maximum possible output length is small and easily calculated, but it's not always this easy, and my guess is that this is why your friend told you not to use sprintf.

Upvotes: 1

Peter R
Peter R

Reputation: 414

If you're on a machine which supports the GNU extensions then you can use asprintf as well. This will allocate heap memory, store the string in it and then give you a pointer to this. Just make sure you free the string when you're done with it.

Upvotes: 1

Andre
Andre

Reputation: 1607

As long as you make sure that the buffer pointed to by mcc is big enough for the resulting string, I see no problem.

Upvotes: 3

Related Questions