Converting string to byte

I am trying to store a MAC address in a config file and then apply it. The problem I am having is that to use it I need it as a byte array, so I am trying to convert the individual bytes such as 5c, but I am always getting “A first chance exception of type ‘System.Exception’ occurred in mscorlib.dll”, so I am guessing I’m missing something on the converting. Below is what I have tried:


var x = Convert.ToByte("5c");
var x = Convert.ToByte("5C");
var x = Convert.ToByte("0x5c");
var x = Convert.ToByte("0x5C");
var x = byte.Parse("5c");
var x = byte.Parse("5C");
var x = byte.Parse("0x5c");
var x = byte.Parse("0x5C");

The full MAC in the file is “5c-86-4a-00-00-df” and I would like to keep it in valid MAC format rather than changing 5c to 92, I am splitting the string, and I have also tried the conversions hard-coded to 2 characters to eliminate any errors with splitting the string.

I appreciate any guidance on what I am doing wrong.

Encoding.UTF8.GetBytes returns the ascii value for each character rather than the byte represented by the pair. I need to get the equivalent of (byte)0x5c. I’m trying to get the byte array to set the MAC address on my ENC28.

The code I am trying to finish is below.


            string Configuration = @ "5c-86-4a-00-00-df
192.168.1.7
192.168.1.1
192.168.1.3
192.168.1.4";
            string[] configs = Configuration.Split('\n');
            string[] cfgs;
            
            cfgs = configs[0].Trim().Split('-');
            byte[] MACAddress = new byte[] { byte.Parse(cfgs[0]), byte.Parse(cfgs[1]), byte.Parse(cfgs[2]), byte.Parse(cfgs[3]), byte.Parse(cfgs[4]), byte.Parse(cfgs[5]) };
            Networking.Adapter.Start(MACAddress, "mip", Networking.InterfaceProfile.Cerberus_Socket6_ENC28);

I have microSD modules on their way, once I get them I am going to move the hard-coded config string to a file on the microSD. That will keep me from having to always change my code when I switch which device I am working on. I have one prod board and one test board. The IPs are easy as I can split on the . and then convert the individual strings to numbers and cast those to bytes. But the strings are proving a bit more difficult.

This is what you need:

http://www.tinyclr.com/codeshare/entry/42

1 Like

Exactly what I needed, thanks! One of these days I might figure out the trick to getting sufficiently narrow search results, I always end up with hundreds of pages.

Thanks for the tip on this one, of course that won’t lift the rest of my search hex.