2

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 !

Mohit S
  • 13,723
  • 6
  • 34
  • 69
dernat71
  • 365
  • 4
  • 16
  • 2
    `1D` is not `18`. its `29` because `D` is 13. also 18 would be `12` – M.kazem Akhgary Nov 12 '15 at 09:36
  • Are you sure that is what you really need? `totalLenghtByte` is `byte` which is numeric datatype and you are trying to store string there. – Andrey Nov 12 '15 at 09:38
  • Yes i think. I'm using this for creating an xbee frame. In xbee frame , 3rd byte is the lenght byte of the request . So i calculate the totalLenght with first line then convert it to hex ( lenght = 18 -> 1D ) and finally i'm trying to convert this hex string to a byte value ( hex : 1D -> byte : 0x1D ) – dernat71 Nov 12 '15 at 09:46
  • Here is answer http://stackoverflow.com/questions/8576296/c-sharp-string-to-hex-hex-to-byte-conversion – makison Nov 12 '15 at 09:50
  • 1
    @M.kazemAkhgary yes sory my mistake. It's because i add 11 to my lenght value (which was 18 in my example ) -> 11+18 = 29 -> 1D :) – dernat71 Nov 12 '15 at 09:50
  • @AlekseyNosik Huuuuuum sounds good ! Thanks a lot !!!! – dernat71 Nov 12 '15 at 09:58

1 Answers1

1

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);

}
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
  • So if i just add 0x at the beginning of the string and then convert it to byte , i'll have : (byte) 0xtheHexString ? Should be what i need ! – dernat71 Nov 12 '15 at 10:06
  • @Nethim No, a byte is a Byte type, a numeric datatype, not a String. It will neber have "0x". You need to convert it to string to append characters to the start of the string. – ElektroStudios Nov 12 '15 at 10:22
  • Ok but in my byte array, datas are defined like that : byte[] requestInByte={0x7E, 0x00 , 0x1D , ... } That's why i don't understand how to have bytes whith 0x.. and not only 7E , 00, 1D ,... – dernat71 Nov 12 '15 at 10:24
  • 0xNumber is a literal C# numeric datatype, is not a string, you can't do what you want. – ElektroStudios Nov 12 '15 at 10:39
  • so simply using byte mybyte= 7E or mybyte=0x7E is the same ? – dernat71 Nov 12 '15 at 11:04