Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display an integer in hex format

Status
Not open for further replies.

mcklsn

Programmer
Mar 16, 2003
40
US
Another newbie question: how do you convert an int to a string for printing, but format it in hex rather than decimal?
 
int iVal ;
string sVal = string.Format("{0,0:X}",iVal);
Example :
string.Format("{0,0:X}",20032003) will return "131AA03" which is 20032003 in hexadecimal.

-obislavu-

 
Thank you. This is very helpful. I have 2 follow-up questions, if that's alright. First, I've searched everything I can find about format strings, and I haven't been able to find out the function of the comma between the 2 zeroes. Can you tell me what it does? Second, I would like to print out bytes of data in the form of 2 hex digits always. If the value of the byte is 1, I want it to print out as 01. If it is 0, I want 00. If it is 255, I want FF. I haven't been able to modify the format string so that it always prints out 2 hex digits, even if the leading one is a zero. How do I do that?
Thanks very much for you help. Trying to learn C# by yourself with just books is difficult, and the tips I have been given here are a great help.
Thanks again.
 
tring s2 = string.Format("{0:00.0}",iVal).TrimEnd('0'); // returns 00., 01., 02. when ival in {1,2,..};

int iVal;
string s3 = string.Format("{0,2:X}",iVal)+".";
// for 0 s3 will be "00."
// for 1 s3 will be "01."
// for 255 s3 will be "FF."

Here is an example to understand the comma in the format e.g. "{0,2:X}"
int a = 9;
int b=99;
int c = a +b;
string s4 = string.Format("The sum of {0,0:00} and {1,0:00} is {2,0:000}",a,b,c);
// s4 ="The sum of 09 and 99 is 109"
The 0,1,2 are associated to the a,b respectively c variable.
0:00, 0:00, 0:000 are associated format for a,b respectively c.

-obislavu-
 
This seemed to work for 2 digit hex numbers, but when I wanted to expand it to 8 digits (32 bit words), it supressed leading zeroes again. I fiddled with it some more, but couldn't get anything to work.
 
I am not sure about exactly what you want but the following statements returns strings in hexa on 8 positions followed by .

int iVal=1;
string s3 = (string.Format("{0,8:X}",iVal)+".").Replace (' ','0');
//s3 will be 00000001.
iVal = 123456789;
string s4 = (string.Format("{0,8:X}",iVal)+".").Replace (' ','0');
//s4 will be 075BCD15.

-obislavu-

 
Thanks for your patience. This is exactly what I want. Your help has been envaluable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top