github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/doc/content/en/docs/javascript/hex2arr.md (about) 1 --- 2 title: "hex2arr" 3 linkTitle: "hex2arr" 4 date: 2021-11-20 5 description: > 6 7 --- 8 9 The `hex2arr(hexString)` function is available in a JavaScript environment, and it converts a hexadecimal string to a byte array (`[]byte`). 10 11 Here's an example implementation of the `hex2arr` function: 12 13 ```javascript 14 hex2arr = function (hexString) { 15 var result = []; 16 while (hexString.length >= 2) { 17 result.push(parseInt(hexString.substring(0, 2), 16)); 18 hexString = hexString.substring(2, hexString.length); 19 } 20 return result; 21 }; 22 ``` 23 more examples: 24 25 ```javascript 26 function hex2arr(hexString) { 27 // Remove all spaces from the string 28 hexString = hexString.replace(/\s/g, ''); 29 30 // Split the string into pairs of characters (each pair represents a byte) 31 var hexPairs = hexString.match(/.{1,2}/g); 32 33 // Convert each pair of characters to a numeric value 34 var byteArr = hexPairs.map(function (hex) { 35 return parseInt(hex, 16); 36 }); 37 38 return byteArr; 39 } 40 ``` 41 42 You can use the `hex2arr` function as follows: 43 44 ```javascript 45 var hexString = "48656C6C6F20576F726C64"; // Hexadecimal representation of "Hello World" 46 var byteArr = hex2arr(hexString); 47 console.log(byteArr); // [ 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 ] 48 ``` 49 50 In this example, the `hex2arr` function takes the hexadecimal string `"48656C6C6F20576F726C64"`, which represents "Hello World" in hexadecimal format. The result of the function is a byte array containing the corresponding ASCII values of the characters.