locked
How to convert string byte array key to byte array RRS feed

  • Question

  • User377613556 posted

    Hi, 

    I got the string byteArray key from the client and now I want to assign that key to a new byte array.

    I am using below code , but getting error.

    // Key..

    string _strkey = "0x84, 0xBC, 0x16, 0xFE, 0x9B, 0xD9, 0x36, 0x80, 0x69, 0x23, 0xC8, 0x49, 0xC9, 0xB8, 0xFD, 0x22, 0x95, 0xF7, 0x39, 0x1F, 0x32, 0xDF, 0x99, 0xEF, 0xA5, 0xAB, 0xCC, 0x72, 0x46, 0xBB, 0x06, 0x8B";

    // converting the string byte array to byte array.
    byte[] Key = _strkey.Split(' ')
    .Select(part => byte.Parse(part, System.Globalization.NumberStyles.AllowHexSpecifier))
    .ToArray();

    Thanks,

    Ram

    Friday, July 7, 2017 10:03 AM

All replies

  • User753101303 posted

    Hi,

    According to https://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(v=vs.110).aspx it allows 0 to 9, A to F (or a to f) but doesn't include the 0x or &h prefix. Also the split is wrong. It should be on ',' rather than on ' ' and you likely should also add the flag that allows leading space as you have spaces in your string.

    Not sure about your exact context but another option is also to initialize directly a byte array from the code using https://msdn.microsoft.com/en-us/library/aa664573(v=vs.71).aspx depending on where you get your actual string.

    Friday, July 7, 2017 11:04 AM
  • User303363814 posted

    var Key = _strkey.Replace("0x","").Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
    .Select(part => byte.Parse(part, System.Globalization.NumberStyles.AllowHexSpecifier))
    .ToArray();

    Friday, July 7, 2017 12:42 PM
  • User-1838255255 posted

    Hi ramakrishnan27,

    According to your description, as far as I know, you need replace the 0x with null, then convert the array item to byte array. Here is complete sample, please check:

    Sample Code:

    protected void Button1_Click(object sender, EventArgs e)
            {
                string _strkey = "0x84, 0xBC, 0x16, 0xFE, 0x9B, 0xD9, 0x36, 0x80, 0x69, 0x23, 0xC8, 0x49, 0xC9, 0xB8, 0xFD, 0x22, 0x95, 0xF7, 0x39, 0x1F, 0x32, 0xDF, 0x99, 0xEF, 0xA5, 0xAB, 0xCC, 0x72, 0x46, 0xBB, 0x06, 0x8B";
                string[] words = _strkey.Split(',');
    
                string[] arr = new string[32];
                for (int i = 0; i < words.Length; i++)
                {
                    arr[i] = words[i].Replace("0x", "").ToString().Trim();
                }
    
                for (int i = 0; i < arr.Length; i++)
                {
                    byte[] array = Encoding.ASCII.GetBytes(arr[i]);
                }
            }

    Best Regards,

    Eric Du

    Saturday, July 8, 2017 3:57 AM