The BitConverter.ToString gives a hexadecimal in the format 'XX-XX-XX-XX'
Is there an opposite method to this so that I can obtain the original byte array from a string as given in this format?
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.
It formats the string as two uppercase hexadecimal characters. In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal. byte.
C# itself doesn't define the endianness. Whenever you convert to bytes, however, you're making a choice. The BitConverter class has an IsLittleEndian field to tell you how it will behave, but it doesn't give the choice. The same goes for BinaryReader/BinaryWriter.
No, but its easy to implement:
string s = "66-6F-6F-62-61-72";
byte[] bytes = s.Split('-')
.Select(x => byte.Parse(x, NumberStyles.HexNumber))
.ToArray();
Use of string.Split, then byte.Parse in a loop is the simplest way. You can squeeze out a little more performance if you know that every byte is padded to two hex digits, there's always exactly one dash in between, by skipping the string.Split and just striding through three characters at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With