Main Site Documentation

Convert string of MAC address to byte


#1

Someone can help me converting a string like that 02:00:30:01:00:07 to a byte.
Because I have to setup mac address reading value from an SD card and pushing it on network interface.
Tried something like that
MAC[0] = Byte.Parse(corrected_mac.Substring(1, 2));
MAC[1] = Byte.Parse(corrected_mac.Substring(3, 2));
MAC[2] = Byte.Parse(corrected_mac.Substring(5, 2));
MAC[3] = Byte.Parse(corrected_mac.Substring(7, 2));
MAC[4] = Byte.Parse(corrected_mac.Substring(9, 2));
MAC[5] = Byte.Parse(corrected_mac.Substring(11, 2));

but it doesn’t work.

Ideas??

Tks


#2

Convert.ToByte(…)?


#3

MAC[0] = (byte)Byte.Parse(corrected_mac.Substring(0, 2));
MAC[1] = (byte)Byte.Parse(corrected_mac.Substring(2, 2));
MAC[2] = (byte)Byte.Parse(corrected_mac.Substring(4, 2));
MAC[3] = (byte)Byte.Parse(corrected_mac.Substring(6, 2));
MAC[4] = (byte)Byte.Parse(corrected_mac.Substring(8, 2));
MAC[5] = (byte)Byte.Parse(corrected_mac.Substring(10, 2));

I found that solution not so look good, but it works :wink:


#4

your solution will not work all the time. It fails with a hex number, which can appear in MAC.

Google “c# hex string to byte” or look at the byte.parse documentation for the number type parameter.


#5

Ok tested and updated with code on google.
now it’s better.

Tks


#6

You can try this class.
Usage:
byte[] _mac = StringToHex.FromString(corrected_mac);

    public static class StringToHex {

        public static byte[] FromString(string value) {
            string[] _peices = value.Split(':');
            byte[] _mac = new byte[6];
            for (int i = 0; i < _mac.Length; i++) {
                _mac[i] = Oclet(_peices[i]);
            }
            return _mac;
        }
        private static byte Oclet(string hexValue) {
            byte _hexResult = 0x00;
            hexValue = hexValue.ToUpper();
            char[] _values = hexValue.ToCharArray();

            for (int i = 0; i < _values.Length; i++) {
                _hexResult *=16;

                if (_values[i] <= (byte)('9') && _values[i] >= (byte)('0')) {
                    _hexResult += (byte)(((byte)_values[i]) - (byte)('0'));
                }
                else if (_values[i] <= (byte)('F') && _values[i] >= (byte)('A')) {
                    _hexResult += (byte)((byte)_values[i] - (byte)('A') + 10);
                }
                else {
                    throw new ArgumentException("Specified value is out of range");
                }
            }
            return _hexResult;
        }
    }