如何将String转换为Bytearray

编程入门 行业动态 更新时间:2024-10-14 00:31:24
本文介绍了如何将String转换为Bytearray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用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

本文发布于:2023-06-08 21:31:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589424.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   String   Bytearray

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!