文档管理中心
FAQ应用框架开发ArkTS语言方舟编程语言(ArkTS)Uint8Array类型和String以及hex如何互相转换

Uint8Array类型和String以及hex如何互相转换

Uint8Array类型和String以及hex实现互相转换,可参考如下代码:

收起
自动换行
深色代码主题
复制
  1. import { buffer, util } from '@kit.ArkTS';
  2. // Convert string to byte stream
  3. function stringToUint8Array(str: string) {
  4. console.info('Convert string to byte stream:' + new Uint8Array(buffer.from(str, 'utf-8').buffer));
  5. return new Uint8Array(buffer.from(str, 'utf-8').buffer);
  6. }
  7. // Byte flow into understandable strings
  8. function uint8ArrayToString(array: Uint8Array) {
  9. let textDecoderOptions: util.TextDecoderOptions = {
  10. fatal: false,
  11. ignoreBOM: true
  12. }
  13. let decodeToStringOptions: util.DecodeToStringOptions = {
  14. stream: false
  15. }
  16. let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
  17. let retStr = textDecoder.decodeToString(array, decodeToStringOptions);
  18. console.info('Byte flow into understandable strings:' + retStr);
  19. return retStr;
  20. }
  21. //Hexadecimal to Uint8Array
  22. function HexStrTouint8Array(data: string): Uint8Array {
  23. console.info('Hexadecimal to Uint8Array:' + new Uint8Array(buffer.from(data, 'hex').buffer));
  24. return new Uint8Array(buffer.from(data, 'hex').buffer);
  25. }
  26. // Uint8Array to hexadecimal
  27. function uint8ArrayToHexStr(data: Uint8Array): string {
  28. let hexString = '';
  29. let i: number;
  30. for (i = 0; i < data.length; i++) {
  31. let char = ('00' + data[i].toString(16)).slice(-2);
  32. hexString += char;
  33. }
  34. console.info('Uint8Array to hexadecimal:' + hexString);
  35. return hexString;
  36. }
  37. let uint8Array: Uint8Array;
  38. @Entry
  39. @Component
  40. struct TypeConversion {
  41. build() {
  42. Column({ space: 12 }) {
  43. Button('Convert string to byte stream')
  44. .onClick(() => {
  45. let str = 'hello';
  46. uint8Array = stringToUint8Array(str);
  47. })
  48. Button('Byte flow string')
  49. .onClick(() => {
  50. if (uint8Array) {
  51. uint8ArrayToString(uint8Array);
  52. }
  53. })
  54. Button('Hexadecimal to Uint8Array')
  55. .onClick(() => {
  56. let data = '05160b22';
  57. HexStrTouint8Array(data);
  58. })
  59. Button('Uint8Array to hexadecimal')
  60. .onClick(() => {
  61. let uint8Array = new Uint8Array([5, 22, 11, 34]);
  62. uint8ArrayToHexStr(uint8Array);
  63. })
  64. }
  65. .width('100%')
  66. .justifyContent(FlexAlign.Center)
  67. }
  68. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词