来自C#的Javascript fromCharCode

时间:2017-12-06 10:52:35

标签: javascript c# fromcharcode

我有一个函数i Javascript,如下所示

// 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;

但我无法找到此行的等效

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

什么可以相当于这条线?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用 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}")));

结果:

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