Javascript 等效于 C# 中的 fromCharCode
Javascript fromCharCode equivalent in C#
我有一个函数 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] ) );
这行相当于什么?
您可以尝试使用 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
我有一个函数 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] ) );
这行相当于什么?
您可以尝试使用 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