3

I know this question asked in different ways but I couldn't find the right answer that fit to react native...

How to convert String to Byte array I react native?

For example I would like the function will be like that:

StringToByteArray('hello')

The output should be something like that: [72,0,101,0,108,0,108,0,111,0]

I have been looking in this post, but it seems the answers are incorrect or invalid...

JJ Redikes
  • 381
  • 5
  • 18

1 Answers1

3

You should try this solution:

 convertStringToByteArray(str){
 String.prototype.encodeHex = function () {
 var bytes = [];
 for (var i = 0; i < this.length; ++i) {
  bytes.push(this.charCodeAt(i));
 }
 return bytes;
 };

 var byteArray = str.encodeHex();
 return byteArray
 }

The way to use this function:

var str = "Hello";
console.log("buffer",this.convertStringToByteArray(str));

//output: [ 72, 101, 108, 108, 111 ]
Tal Shani
  • 560
  • 7
  • 23