1

How can I convert a string like this

string s = "00-11-22-33-44-55-66-77-88-99-00-11-22-3A-4A-5A";

to a byte array like this

byte[] b = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22, 0x3A, 0x4A, 0x5A };
2
  • What language is this? And what you have tried? Commented Mar 16, 2014 at 12:16
  • What language is this? Commented Mar 16, 2014 at 12:17

4 Answers 4

4
s
.Split('-')
.Select(part => byte.Parse(part, System.Globalization.NumberStyles.HexNumber))
.ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Linq always wins in my book! :)
It is HexNumber, not Hex.
0

First off, remove all dashes from your string.

string str = "00-11-22-33-44-55-66-77-88-99-00-11-22-3A-4A-5A";

// remove all except hex compliant chars
Regex rgx = new Regex("[^a-fA-F0-9]");  

// now do the stripping
str = rgx.Replace(str, "");

Better stripping and checking if the string is actually hex can be implemented here but for this lets keep it simple.

Then use this function

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Then

// actually do the converting
StringToByteArray(str);

Comments

0

Try this:

string s = "00-11-22-33-44-55-66-77-88-99-00-11-22-3A-4A-5A";
var strArray = s.Split('-');
var byteArr = (from item in strArray
              select Byte.Parse(item, System.Globalization.NumberStyles.HexNumber)).ToArray();

Comments

-1

Do following steps: Parse all of the string using '-' character and output all of the substrings in an string array, than, add "Ox" at the beginning of all strings in array. Codes below can easily solve your problem in c#.

1 Comment

They are still strings then... Not a byte array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.