【问题标题】:How to convert String into Hex nodejs如何将字符串转换为十六进制 nodejs
【发布时间】:2018-05-11 07:53:51
【问题描述】:

我一直在寻找一些标准函数,例如十六进制到字符串但相反, 我想将String转换为Hex,但我只找到了这个function...

// Example of convert hex to String
hex.toString('utf-8')

【问题讨论】:

    标签: node.js string hex


    【解决方案1】:

    在 NodeJS 中,使用Buffer 将字符串转换为十六进制。

    Buffer.from('hello world', 'utf8').toString('hex');
    

    关于其工作原理的简单示例:

    const bufferText = Buffer.from('hello world', 'utf8'); // or Buffer.from('hello world')
    console.log(bufferText); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
    
    const text = bufferText.toString('hex');
    // To get hex
    console.log(text); // 68656c6c6f20776f726c64
    
    console.log(bufferText.toString()); // or toString('utf8')
    // hello world
    
    //one single line
    Buffer.from('hello world').toString('hex')
    

    【讨论】:

    • 我有一个 base64 字符串,其中包含一个冒号,当我将其转换为十六进制然后返回 base64 时,它会去掉冒号。这解决了它谢谢!
    • 这适用于react-native只需要安装yarn add buffer
    • 要获得均匀间隔的 2 个字母输出,只需执行以下操作:Buffer.from('hello world', 'utf8').toString('hex').replace(/../g, '$&amp; ')
    【解决方案2】:

    你可以使用如下函数:

      function stringToHex(str) {
    
      //converting string into buffer
       let bufStr = Buffer.from(str, 'utf8');
    
      //with buffer, you can convert it into hex with following code
       return bufStr.toString('hex');
    
       }
    
     stringToHex('some string here'); 
    

    【讨论】:

      【解决方案3】:

      NPM amrhextotext,简单的文本转十六进制和十六进制转文本

      安装

      npm i amrhextotext
      

      用法:

      const text = 'test text'
      const hex = '746573742074657874'
      
      const convert = require('amrhextotext')
      
      //convert text to hex
      let hexSample = convert.textToHex(text)
      //Result: 746573742074657874
      
      //Convert hex to text
      let textSample = convert.hexToUtf8(hex)
      //Result: test text
      

      注意:来源页面

      【讨论】:

      • 嗨 Diego 欢迎来到 SO,也许你可以添加一个包的链接,甚至添加一个如何使用它的示例
      猜你喜欢
      • 2013-02-07
      • 2017-08-23
      • 2014-03-19
      • 2011-08-25
      • 2014-04-28
      • 2018-01-31
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多