4

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
  • 421
  • 6
  • 19

1 Answers1

5

You should try this solution:

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

The way to use this function:

console.log(convertStringToByteArray("Hello"));
// [ 72, 101, 108, 108, 111 ]
cdosborn
  • 3,111
  • 29
  • 30
Tal Shani
  • 660
  • 1
  • 9
  • 26