如何将String转换为Bytearray [英] How to convert a String to Bytearray

查看:153
本文介绍了如何将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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆