Converting string to equivalent byte hex in c#

前端 未结 3 2079
名媛妹妹
名媛妹妹 2021-01-29 14:08

I have an incoming string 68016101061B4A60193390662046804020422044204000420040402060226024676DB16 and I want to convert into 0x68 0x01 0x61 0x01 0x06 0x1B 0x4

3条回答
  •  半阙折子戏
    2021-01-29 15:03

    You can use a regular expression to do this:

    var regex = new Regex(@"(\d{2})");
    
    string aString = "040204220442040004200404020602260246";
    string replaced = regex.Replace(aString, "x$1 ");
    

    Fiddle

    EDIT It seems like you need bytes instead of a string, you can use one of the Linq based answers suggested here or a simple loop:

    if ((aString.Length % 2) != 0)
    {
        // Handle invalid input
    }
    
    var bytes = new byte[aString.Length / 2];
    
    int index = 0;
    for (int i = 0; i < aString.Length; i += 2)
    {
        string digits = aString.Substring(i, 2);
        byte aByte = (byte)int.Parse(digits, NumberStyles.HexNumber);
    
        bytes[index++] = aByte;
    }
    
    port.Write(bytes, 0, bytes.Length);
    

    Note that if GC pressure became an issue, you could use ReadOnlySpan.

    Fiddle

提交回复
热议问题