如何使用JavaScript在bytearray中转换字符串。输出应该等于下面的C#代码。
How can I convert a string in bytearray using JavaScript. Output should be equivalent of the below C# code.
UnicodeEncoding encoding = new UnicodeEncoding(); byte[] bytes = encoding.GetBytes(AnyString);由于UnicodeEncoding默认为UTF-16,具有Little-Endianness。
As UnicodeEncoding is by default of UTF-16 with Little-Endianness.
编辑:我要求使用上面的C#代码将bytearray生成的客户端与服务器端生成的客户端匹配。
I have a requirement to match the bytearray generated client side with the one generated at server side using the above C# code.
推荐答案在C#中运行此
UnicodeEncoding encoding = new UnicodeEncoding(); byte[] bytes = encoding.GetBytes("Hello");将创建一个数组
72,0,101,0,108,0,108,0,111,0
对于代码大于255的字符,看起来像这样
For a character which the code is greater than 255 it will look like this
如果你想在JavaScript中有一个非常相似的行为,你可以这样做(v2是一个更强大的解决方案,而原始版本只适用于0x00~0xff)
If you want a very similar behavior in JavaScript you can do this (v2 is a bit more robust solution, while the original version will only work for 0x00 ~ 0xff)
var str = "Hello竜"; var bytes = []; // char codes var bytesv2 = []; // char codes for (var i = 0; i < str.length; ++i) { var code = str.charCodeAt(i); bytes = bytes.concat([code]); bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]); } // 72, 101, 108, 108, 111, 31452 console.log('bytes', bytes.join(', ')); // 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 220, 122 console.log('bytesv2', bytesv2.join(', '));
更多推荐
如何将String转换为Bytearray
发布评论