Reputation: 550
I have hex representing ascii values stored in the following format.
// Hex reperesention of ascii string
string hexString = "48-65-6C-6C-6F-20-77-6F-72-6C-64-21-21-21";
// Could someone help fill in the blanks here?
private string hexConverter(string hexString)
{
string asciiCharString;
// Convert it
return asciiCharString;
}
so when called;
string s = hexConverter(hexString);
string s would contain "Hello world!!!" in this case.
Upvotes: 1
Views: 1565
Reputation: 10507
Lets break this question down...
So you first want to break up the string based on hyphens ('-'). To do this, we would use Split('-')
. This yields an array of strings.
hexString.Split('-')
We then want to convert those strings into a number. Because this is ASCII, lets convert each string into a byte
.
byte.Parse(value, System.Globalization.NumberStyles.HexNumber)
Once we have a bunch of byte
s, then we can convert it into a String
using an ASCII encoder (Encoding.ASCII.GetString()
)
So to put it all together:
static string hexConverter(string hexString)
{
return Encoding.ASCII.GetString(fetchBytes(hexString).ToArray());
}
static IEnumerable<byte> fetchBytes(String hexString)
{
foreach (var value in hexString.Split('-'))
yield return byte.Parse(value, System.Globalization.NumberStyles.HexNumber);
}
Encoding
If at a later date you decide you need UTF-8 or something else, then all you would need to do is replace Encoding.ASCII
with Encoding.UTF8
, and the rest of the logic will still work.
Upvotes: 0
Reputation: 2876
private string hexConverter(string hexString)
{
string asciiCharString ="" ;
var splitResult = hexString.Split('-');
foreach (string hexChar in splitResult )
{
var byteChar = int.Parse(hexChar, NumberStyles.HexNumber);
asciiCharString += (char)byteChar;
}
return asciiCharString;
}
// Test
private void button1_Click(object sender, EventArgs e)
{
string hexString = "48-65-6C-6C-6F-20-77-6F-72-6C-64-21-21-21";
string asciiString = hexConverter(hexString);
MessageBox.Show(asciiString);
}
Upvotes: 0
Reputation: 6793
var convertedString = new StringBuilder();
foreach(var hex in hexString.Split('-'))
{
var unicode = int.Parse(hex, NumberStyles.HexNumber);
convertedString.Append((char)unicode);
}
return convertedString.ToString();
Upvotes: 2