I'm trying to do some conversion and would like to use Linq to achieve the following,
Decimal to Hex, Decimal to Ascii, Hex to Decimal, Hex to Ascii
Can someone please show me how to do this efficently in Linq? I'll be displaying the output into textboxes.
Also, I have a prefix and delimiter field that will also need to be included,
Example:
string input = txtAscii.Text;
string delim = txtDelimiter.Text;
string prefix = txtPrefix.Text;
if (checkBox1.Checked == true && string.IsNullOrEmpty(delim)) delim = " ";
//Linq, Ascii to Decimal.
txtDecimal.Text = string.Join(delim, input.Select(c => prefix + ((int)c).ToString()));
Thanks all.
LINQ is for querying collections, not converting values. It is wrong to say you want to use LINQ to convert X to Y.
That said, here's the building blocks you need:
// string in decimal form to int
Int32.Parse("12345");
// string in hexadecimal form to int
Int32.Parse("ABCDE", NumberStyles.HexNumber);
// int to string in decimal form
12345.ToString();
// int to string in hexadecimal form
12345.ToString("x");
Then to do something like converting between decimal form to hexadecimal form:
var inDecimal = "12345";
var asInt = Int32.Parse(inDecimal);
var asHex = asInt.ToString("x");
Your "ASCII to (hexa)decimal" conversions could be done with a little bit of LINQ using the above building blocks. Assuming you mean the (hexa)decimal representation of each character's ASCII code:
var str = "FOOBAR!";
var asAsciiInt = String.Join(" ", str.Select(c => (int)c));
var asAsciiHex = String.Join(" ", str.Select(c => ((int)c).ToString("x2")));
// asAsciiInt == "70 79 79 66 65 82 33"
// asAsciiHex == "46 4f 4f 42 41 52 21"
var asciiInt = "70 79 79 66 65 82 33";
var charStrs = asciiInt.Split();
var asStr = String.Concat(charStrs.Select(cs => (char)Int32.Parse(cs)));
// asStr == "FOOBAR!"
var asciiHex = "46 4f 4f 42 41 52 21";
var charStrs = asciiHex.Split();
var asStr = String.Concat(charStrs.Select(cs => (char)Int32.Parse(cs, NumberStyles.HexNumber)));
// asStr == "FOOBAR!"
To convert numeric value to hex is dead easy.
Decimal d = 10M;
d.ToString("X")
I am however utterly confused by what you mean "decimal to ascii"
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