How much smaller and efficient could I make this code snippet?

Hi,

As a heads up I openly admit I am new to programming and computer science (and related) subjects but have taken interest in learning them lately.

Having a bit of a poor education history in math and the logic skills that teaches you, combined with lack of programming experience some things can seem really silly to me. Anyways, here it is. I have lots of strings like this:

 string MyString = "64 A1 0 0 0 0 6A FF 68 ?? ?? ?? ?? 50 64 89 25 0 0 0 0 A1 ?? ?? ?? ?? 81 EC C8 0 0 0 53 55 33 DB 56 57 3B C3"; 

I want to store them in a text file and load them up. From here I would like to convert the above string to two types:

A byte[] containing all values as a byte except with the question marks as a zero byte, but still included. A string with all individual strings between spaces represented as one single X. So "A1" would need to become "x", and not "xx" etc. 

Above string example would convert to:

 byte[] extractedBytes = new byte[] 100, 161, 0, 0, 0, 0, 106, 255, 104, 0, 0, 0, 0, 80, 100, 137,37, 0, 0, 0, 0, 161, 0, 0, 0, 0, 129, 236, 0xC8, 0, 0, 0, 0x53, 0x55, 0x33, 0xDB, 0x56, 0x57, 0x3B, 0xC3 string extractedString = "xxxxxxxxx????xxxxxxxxx????xxxxxxxxxxxxxx" 

This is not home work or anything just a personal problem I wanted to solve for fun, since I use many of these combinations and add many of them. So I stored them in a xml file out side of my application as one single string then wrote the below to convert them on load up, as it was super confusing to have a huge page of tons of bytes and strings when I needed to find,modify,add etc them.

Convert to byte:

 private static IEnumerable<byte> GetBytesFromPattern(string pattern) { var split = pattern.Insert(0, "\\x").Replace(" ", "\\x").Replace("??", "0").Split(new[] {'\\', 'x'}, StringSplitOptions.RemoveEmptyEntries); var ret = new byte[split.Length]; for (var i = 0; i < split.Length; i++) { ret[i] = byte.Parse(split[i], NumberStyles.HexNumber); } return ret; } 

Convert to new string:

 private static string TryGetMaskFromPattern(string pattern) { var mask = new StringBuilder(pattern).Replace("??", "?") .ToString() .Split(' ') .Select(s => s.Contains('?') ? '?' : 'x').ToArray(); return new string(mask); } 

Anyone wanting to show me how they would do it easier and smaller feel free! Maybe some cool usage of the out feature in order to not split it so many ways?

by JacobKemple via /r/csharp

Leave a Reply