I've been working on a char to hex converter all day, and it's working.

Except for one part.

I've got an unsigned short I want seperated into the two hex values. I've been beating on this stupid bit of code all day, and it's just not working.
The hex representation is to be stored in a CString, because I've found they are very handy.
itoa doesn't help, and the cstring .Format doesn't seem to allow printing as a char array, either.

The closest I've gotten is assigning the correct byte value(but not as characters) in a CString.

CString str1,str2;
unsigned short test = 0x1234;

str2 = (test>>8); //this gives test having '12', as an integer value, and useless symbol.
str1=str2; /*Or with concatenation, doesn't help... Doing this because str1 is going to be displayed on the screen, but str2 is used for formatting.*/

I'm sure the solution is really mindnumbingly simple, but I've been somehow able to struggle with this stupid thing for hours.

Thanks for your time.

not quite certain what you want. Do you want to convert the unsigned short to CString? CString's Format function is identical to sprintf() and printf().

CString str;
unsigned short test = 0x1234;
str.Format("%X", test);

Of course if you display the result, the string will be "1234".

I'm looking to break it into 12 and 34 such that when I place it into str1, it can be concatenated with += and a space, such that str1 would read as
12 34

Not two ascii symbols that evaluate as 12 and 34.

I found out that I'm really a twit at times. Hexidecimal means radix 16, not 8.

However, the solution I'm using goes like this:

CString line, temp; //Display and formatting strings, respectively.
char * bytePtr;
unsigned short test; //Some value...
	bytePtr= &test;
	bytePtr++;
	if((*bytePtr&0x00FF)<16)
		temp.Format("0%X ",(*bytePtr&0x00FF));
	else
		temp.Format("%X ",(*bytePtr&0x00FF));
	
	line+=temp;
	bytePtr--;

	if((*bytePtr&0x00FF)<16)
		temp.Format("0%X:",(*bytePtr&0x00FF));
	else
		temp.Format("%X:",(*bytePtr&0x00FF));
	line+=temp;
CString str;
unsigned short test = 0x1234;
str.Format("%04X", test);
CString n1 = str.Left(2);
CString n2 = str.Right(2);
// now put it back
str = n1 + " " + n2;

That's certainly shorter in code length.
Should I use that method instead of the one I posted?
Since it works either way, is there a definite benefit in memory or speed, or are those concerns too trival to bother thinking about?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.