Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently convert an unsigned short to a char*

What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25').

I'd like to avoid things such as getting (std::string) strings involved. Performance is important in this case since this conversion will need to happen quickly and often.

I was looking into things such as using sprintf but would like to explorer any and all ideas.

like image 885
jCuga Avatar asked Jan 18 '11 21:01

jCuga


2 Answers

First off, do it right, then do it fast--only optimize if you can see for certain that a piece of code is not performant.

snprintf() into a buffer will do what you want. Is it the fastest possible solution? Not at all. But it is among the simplest, and it will suffice to get your code into a working state. From there, if you see that those calls to snprintf() are so laborious that they need to be optimized, then and only then seek out a faster solution.

like image 186
Jonathan Grynspan Avatar answered Sep 21 '22 02:09

Jonathan Grynspan


An array of strings such that

array[25] = "25";
array[26] = "26";

array[255] = "255";

maybe? You could write a small program that generates the table source code for you quite easily, and then use this file in your project.

Edit: I don't get what you mean by you don't want to ge strings involved.

like image 23
James Avatar answered Sep 20 '22 02:09

James