How to convert a hexadecimal string to Uint8Array and back in JavaScript?

后端 未结 3 1052
猫巷女王i
猫巷女王i 2020-12-06 16:18

I want to convert a hexadecimal string like bada55 into a Uint8Array and back again.

相关标签:
3条回答
  • 2020-12-06 16:32

    Node.js

    For JavaScript running on Node you can do this:

    const hexString = 'bada55';
    
    const hex = Uint8Array.from(Buffer.from(hexString, 'hex'));
    
    const backToHexString = Buffer.from(hex).toString('hex');
    

    (source: this answer by @Teneff, shared with permission)

    0 讨论(0)
  • 2020-12-06 16:33

    Here's a solution in native JavaScript:

    var string = 'bada55';
    var bytes = new Uint8Array(Math.ceil(string.length / 2));
    for (var i = 0; i < bytes.length; i++) bytes[i] = parseInt(string.substr(i * 2, 2), 16);
    console.log(bytes);
    
    var convertedBack = '';
    for (var i = 0; i < bytes.length; i++) {
      if (bytes[i] < 16) convertedBack += '0';
      convertedBack += bytes[i].toString(16);
    }
    console.log(convertedBack);
    
    0 讨论(0)
  • 2020-12-06 16:48

    Vanilla JS:

    const fromHexString = hexString =>
      new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
    
    const toHexString = bytes =>
      bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
    
    console.log(toHexString(new Uint8Array([0, 1, 2, 42, 100, 101, 102, 255])))
    console.log(fromHexString('0001022a646566ff'))
    

    Note: this method trusts its input. If the provided input has a length of 0, an error will be thrown. If the length of the hex-encoded buffer is not divisible by 2, the final byte will be parsed as if it were prepended with a 0 (e.g. aaa is interpreted as aa0a).

    If the hex is potentially malformed or empty (e.g. user input), check its length and handle the error before calling this method, e.g.:

    const missingLetter = 'abc';
    if(missingLetter.length === 0 || missingLetter.length % 2 !== 0){
      throw new Error(`The string "${missingLetter}" is not valid hex.`)
    }
    fromHexString(missingLetter);
    

    Source: the Libauth library (hexToBin method)

    0 讨论(0)
提交回复
热议问题