Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to Bytearray

Tags:

javascript

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.

like image 643
shas Avatar asked Jun 03 '11 10:06

shas


People also ask

How do I create a Bytearray file?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.

How do you create a byte array from a string in Python?

Python binary string to byte array In this example, I have taken a binary string as string = “11000010110001001100011”. To convert the binary string to a byte array. I have used new_string = bytearray(string, “ascii”). The bytearray() method returns the byte array object.

Which method converts string to byte value syntax?

The simplest way to do so is using parseByte() method of Byte class in java.


1 Answers

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); 
like image 63
Jin Avatar answered Oct 02 '22 10:10

Jin