Home > OS >  How to concert a hexadecimal expression to string?
How to concert a hexadecimal expression to string?

Time:07-25

I am trying to convert some data in hexadecimal into string using this code:

hex = hex.Replace("0x", "");
hex = hex.Trim();

StringBuilder stringBuilder = new StringBuilder();

for (int i = 0; i < hex.Length; i  = 2)
{ 
    string hs = hex.Substring(i, 2);
    stringBuilder.Append(Convert.ToChar(Convert.ToInt32(hs,16)));            
}

Hex being in the format "0x53 0x50 0x31 0x32 0x33 0x34 0x35 0x36".

However, I keep getting an error

System.FormatException: 'Could not find any recognizable digits'

Hope to understand what is the issue and how to resolve it. Many thanks!

CodePudding user response:

Like so?

var input  = "0x53 0x50 0x31 0x32 0x33 0x34 0x35 0x36";

var result = input.Split(" ").Select(item => (char)Convert.ToInt32(item, 16)).ToList();

CodePudding user response:

If I have understood you right, you want to turn each encoding like 0x53 into corresponding char (S). If it's your case we can query the source string with a help of Linq and combine the result back into string with a help of string.Concat:

using System.Linq;

string source = "0x53 0x50 0x31 0x32 0x33 0x34 0x35 0x36";

// SP123456
string result = string.Concat(source
  .Split(' ', StringSplitOptions.RemoveEmptyEntries)
  .Select(item => (char)int.Parse(item.Substring(item.IndexOf('x')   1), 
                                  NumberStyles.HexNumber)));

Yet another possibility is Regular Expressions:

using System.Text.RegularExpressions;

...

string source = "0x53 0x50 0x31 0x32 0x33 0x34 0x35 0x36";

var result = Regex.Replace(
  source, 
@"\s*0x[0-9a-fA-F]{2}\s*", 
  m => ((char)Convert.ToInt32(m.Value.Trim(), 16)).ToString());

CodePudding user response:

One simple solution is to use Convert.FromHexString, after stripping out the 0x

var hex = "0x53 0x50 0x31 0x32 0x33 0x34 0x35 0x36";
var span = hex.Replace(" 0x", "").Substring(2);
var bytes = Convert.FromHexString(span);
var result = Encoding.UTF8.GetString(bytes);

dotnetfiddle

  • Related