Javascript fromCharCode equivalent in C#

5.1k Views Asked by At

I have a function i Javascript which looks like the following

// Use this to convert "0123DEF01234" (hex string) to
// binary data based on 0x01 0x23 0xDE 0xF0 0x12 0x34

hex = "0123456789ABCDEFFEDCBA98765432100123456789ABCDEF";

hex = hex.replace(/\s/g,""); // eliminate spaces

var keyar = hex.match(/../g); // break into array of doublets

var s="";  // holder for our return value

for(var i=0;i<keyar.length;i++) 
        s += String.fromCharCode( Number( "0x" + keyar[i] ) );

return s;

but i am not able to find the equivalent of this line

        s += String.fromCharCode( Number( "0x" + keyar[i] ) );

what can be the equivalent of this line?

1

There are 1 best solutions below

0
On BEST ANSWER

You can try using Linq:

using System.Linq;

...

string hex = "0123456789ABCDEFFEDCBA98765432100123456789ABCDEF";

// Eliminating white spaces
hex = string.Concat(hex.Where(c => !char.IsWhiteSpace(c))); 

// Let "binary data based on 0x01 0x23 0xDE..." be an array
byte[] result = Enumerable
  .Range(0, hex.Length / 2) // we have hex.Length / 2 pairs
  .Select(index => Convert.ToByte(hex.Substring(index * 2, 2), 16))
  .ToArray();

// Test (let's print out the result array with items in the hex format)
Console.WriteLine(string.Join(" ", result.Select(b => $"0x{b:X2}")));

Outcome:

0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF 0xFE 0xDC 0xBA 0x98 0x76 0x54 0x32 0x10 0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF