-1

In C# I am trying to use a string that is already in bytes to array of bytes, I can't use Linq since I am using 2.0 framework. I just want to use the string as a byte array, so converting it.

Would like to do:

string MYBytes ="{ 0x4D, 0x5A, 0x90 }";
byte[] getBytes = MYBytes;
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user3732111
  • 151
  • 1
  • 2
  • 8

2 Answers2

1

Basically, you want to split up the string and parse each item individually as a byte. Here is one way to do it:

Update

Looks like I pasted in the wrong fiddle link. Here is the code with he correct link.

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {

        string MYBytes = "{ 0x4D, 0x5A, 0x90 }";

        string[] hexParts = MYBytes.Split(new char[] { ',', '{', '}' }, StringSplitOptions.RemoveEmptyEntries);

        byte[] bytes = new byte[hexParts.Length];

        for(int i = 0; i < hexParts.Length; i++)
            bytes[i] = Byte.Parse(hexParts[i].Substring(3), NumberStyles.HexNumber);


        foreach(byte b in bytes)
            Console.WriteLine("{0:X2}", b);
    }
}

https://dotnetfiddle.net/gRMEOM

Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
0

Something like this should work => Encoding.UTF8.GetBytes("4d5a90", 0, resultArray, 0)

See http://msdn.microsoft.com/en-us/library/xsy6z64h(v=vs.110).aspx

See also How can I convert a hex string to a byte array?

Or use unsafe code

To get a byte

unsafe { fixed(char* s = someString) { byte b = s[0]; }}

To get a fixed amount of bytes

unsafe { fixed(char* s = someString) fixed(byte * bz = (byte*) s) fixed byte[3] b = bz; }

I think you can skip the fixing to byte * too

unsafe { fixed(char* s = someString) fixed byte[3] b = (byte *)s; }

Community
  • 1
  • 1
Jay
  • 3,276
  • 1
  • 28
  • 38
  • This is converting the text to bytes, I do not want to convert the actual value of the string to a byte I just want to use the sting's value as the byte value. – user3732111 Jun 12 '14 at 01:25
  • Well you have a fundamental problem... Try unsafe code... – Jay Jun 12 '14 at 01:26