Convert From HEX

M

MDB

Hello all, I am not sure if I am using the correct verbiage however, I need
to convert  to 02. I believe  is a hex string? And I need to know the
into value but I need the 02 value not just 2.
 
N

Nicholas Paldino [.NET/C# MVP]

MDB,

If you have any character in a char variable, you can just cast that to
an int, and then use the ToString method to format the output, like so:

// Convert the char c to a hex string.
string hexString = ((int) c).ToString("x");

However, this will not let you know if you need two characters or not.
You can then just tack the leading zero on if it is not there.

// If the length is less than what is required, then tack the leading
// zeros on.
if (hexString.Length < 2)
{
// Tack the leading zeros on.
hexString = new string('0', 2 - hexString.Length) + hexString;
}

I've coded it this way so you could replace 2 with a constant, depending
on whether or not your string length changes.

Hope this helps.
 
M

MDB

Thank you, it does help!


Nicholas Paldino said:
MDB,

If you have any character in a char variable, you can just cast that to
an int, and then use the ToString method to format the output, like so:

// Convert the char c to a hex string.
string hexString = ((int) c).ToString("x");

However, this will not let you know if you need two characters or not.
You can then just tack the leading zero on if it is not there.

// If the length is less than what is required, then tack the leading
// zeros on.
if (hexString.Length < 2)
{
// Tack the leading zeros on.
hexString = new string('0', 2 - hexString.Length) + hexString;
}

I've coded it this way so you could replace 2 with a constant,
depending on whether or not your string length changes.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

MDB said:
Hello all, I am not sure if I am using the correct verbiage however, I
need to convert  to 02. I believe  is a hex string? And I need to know
the into value but I need the 02 value not just 2.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top