dernat71
dernat71

Reputation: 467

How to convert an hex to the 0x... byte format (C#)

I'd like to convert an int to hex string (this part is OK) and then convert the hex string to the byte format 0x(theHexString) in order to use it into an array. For the moment I've got that code :

// Calculate the int that will be convert to Hex string
int totalLenght=11+request.Length;  
// Try to convert it into byte
byte totalLenghtByte=Convert.ToByte( totalLenght.ToString("X"));  
// put it into an array of bytes
xbeeFrame[2] =(totalLenghtByte); 

For example, the int value is 18 and so the Hex string is 1D (Great !). But the problem is that I don't know if I've to do something else in order to get the 0x1D byte ...

Thank for your help !

Upvotes: 2

Views: 3111

Answers (1)

ElektroStudios
ElektroStudios

Reputation: 20474

Try use the overload of Convert.ToInt32 method that takes a numeric base from:

int int32Value = Convert.ToInt32("1D", fromBase: 16);

byte byteValue = Convert.ToByte(int32Value);

I'm not sure if understood the question.

If what you mean is you want to convert an Hexadecimal value to its C# representation ("0xVALUE") then just add that chars at the beginning of the resulting Hexadecimal string:

"1D".Insert(0, "0x");

Anyways, I made this function that will help you:

/// <summary>
/// Specifies language style to represent an Hexadecimal value
/// </summary>
public enum HexadecimalStyle : int
{

    /// <summary>
    /// C# Hexadecimal syntax.
    /// </summary>
    CSharp = 0,

    /// <summary>
    /// Visual Basic.Net Hexadecimal syntax.
    /// </summary>
    VbNet = 1

}


/// ----------------------------------------------------------------------------------------------------
/// <summary>
/// Converts an Hexadecimal value to its corresponding representation in the specified language syntax.
/// </summary>
/// ----------------------------------------------------------------------------------------------------
/// <example> This is a code example.
/// <code>
/// Dim value As String = HexadecimalConvert(HexadecimalStyle.CSharp, "48 65 6C 6C 6F 20 57")
/// Dim value As String = HexadecimalConvert(HexadecimalStyle.VbNet, "48 65 6C 6C 6F 20 57")
/// </code>
/// </example>
/// ----------------------------------------------------------------------------------------------------
/// <param name="style">
/// The <see cref="CryptoUtil.HexadecimalStyle"/> to represent the Hexadecimal value.
/// </param>
/// 
/// <param name="value">
/// The Hexadecimal value.
/// </param>
/// 
/// <param name="separator">
/// The string used to separate Hexadecimal sequences.
/// </param>
/// ----------------------------------------------------------------------------------------------------
/// <returns>
/// The resulting value.
/// </returns>
/// ----------------------------------------------------------------------------------------------------
/// <exception cref="InvalidEnumArgumentException">
/// style
/// </exception>
/// ----------------------------------------------------------------------------------------------------
[DebuggerStepThrough()]
public string HexadecimalConvert(HexadecimalStyle style, string value, string separator = "")
{

    string styleFormat = "";

    switch (style) {

        case CryptoUtil.HexadecimalStyle.CSharp:
            styleFormat = "0x{0}";

            break;
        case CryptoUtil.HexadecimalStyle.VbNet:
            styleFormat = "&H{0}";

            break;
        default:

            throw new InvalidEnumArgumentException(argumentName: "style", invalidValue: style, enumClass: typeof(HexadecimalStyle));
    }

    if (!string.IsNullOrEmpty(separator)) {
        value = value.Replace(separator, "");
    }


    if ((value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) || (value.StartsWith("&H", StringComparison.OrdinalIgnoreCase))) {
        value = value.Substring(2);

    }

    return string.Format(styleFormat, Convert.ToString(value).ToUpper);

}

Upvotes: 1

Related Questions