admin管理员组

文章数量:1134247

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

As UnicodeEncoding is by default of UTF-16 with Little-Endianness.

Edit: I have a requirement to match the bytearray generated client side with the one generated at server side using the above C# code.

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

As UnicodeEncoding is by default of UTF-16 with Little-Endianness.

Edit: I have a requirement to match the bytearray generated client side with the one generated at server side using the above C# code.

Share Improve this question edited Feb 17, 2018 at 0:06 Jason Aller 3,64428 gold badges41 silver badges39 bronze badges asked Jun 3, 2011 at 10:56 shasshas 1,4312 gold badges11 silver badges10 bronze badges 9
  • 3 javascript is not exactly best-known for being easy to use with BLOBs - why don't you just send the string in JSON? – Marc Gravell Commented Jun 3, 2011 at 10:58
  • Maybe you can take a look here .. – V4Vendetta Commented Jun 3, 2011 at 11:02
  • 2 A Javascript string is UTF-16, or did you know this already? – Kevin Commented Jun 3, 2011 at 11:02
  • 2 First of all why you need to convert this in javascript? – BreakHead Commented Jun 3, 2011 at 11:07
  • 22 Strings are not encoded. Yes, internally they are represented as bytes and they have an encoding, but that's essentially meaningless at the scripting level. Strings are logical collections of characters. To encode a character, you must explicitly choose an encoding scheme, which you can use to transform each character code into a sequence of one or more bytes. The answers to this question below are garbage, as they call charCodeAt and stick its value into an array called "bytes". Hello! charCodeAt can return values greater than 255, so it's not a byte! – Triynko Commented Aug 6, 2013 at 21:15
 |  Show 4 more comments

12 Answers 12

Reset to default 80 +50

Update 2018 - The easiest way in 2018 should be TextEncoder

let utf8Encode = new TextEncoder();
utf8Encode.encode("abc");
// Uint8Array [ 97, 98, 99 ]

Caveats - The returned element is a Uint8Array, and not all browsers support it.

If you are looking for a solution that works in node.js, you can use this:

var myBuffer = [];
var str = 'Stack Overflow';
var buffer = new Buffer(str, 'utf16le');
for (var i = 0; i < buffer.length; i++) {
    myBuffer.push(buffer[i]);
}

console.log(myBuffer);

In C# running this

UnicodeEncoding encoding = new UnicodeEncoding();
byte[] bytes = encoding.GetBytes("Hello");

Will create an array with

72,0,101,0,108,0,108,0,111,0

For a character which the code is greater than 255 it will look like this

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(', '));

UTF-16 Byte Array

JavaScript encodes strings as UTF-16, just like C#'s UnicodeEncoding, so creating a byte array is relatively straightforward.

JavaScript's charCodeAt() returns a 16-bit code unit (aka a 2-byte integer between 0 and 65535). You can split it into distinct bytes using the following:

function strToUtf16Bytes(str) {
  const bytes = [];
  for (ii = 0; ii < str.length; ii++) {
    const code = str.charCodeAt(ii); // x00-xFFFF
    bytes.push(code & 255, code >> 8); // low, high
  }
  return bytes;
}

For example:

strToUtf16Bytes('

本文标签: javascriptHow to convert a String to BytearrayStack Overflow