Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite Method to BitConverter.ToString?

Tags:

c#

hex

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?

like image 523
cam Avatar asked Mar 27 '10 23:03

cam


People also ask

How do you convert hex to bytes?

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.

What is ToString X2?

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.

Is Little Endian C#?

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.


2 Answers

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();
like image 108
Mark Byers Avatar answered Oct 23 '22 17:10

Mark Byers


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.

like image 34
Ben Voigt Avatar answered Oct 23 '22 15:10

Ben Voigt