如何在javascript中生成随机的十六进制字符串

Ale*_*isi 13 javascript lodash

如何生成仅包含给定长度的十六进制字符 (0123456789abcdef) 的随机字符串?

Ami*_*ano 47

NodeJS 用户

您可以使用模块中可用的randomBytescrypto来生成给定大小的加密强伪随机数据。您可以轻松地将其转换为十六进制。

import crypto from "crypto";

const randomString = crypto.randomBytes(8).toString("hex");

console.log(randomString)  // ee48d32e6c724c4d
Run Code Online (Sandbox Code Playgroud)

上面的代码片段生成一个随机的 8 字节十六进制数,您可以根据需要操纵长度。


zer*_*0ne 24

使用扩展运算符和 .map()


演示 1

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

console.log(genRanHex(6));
console.log(genRanHex(12));
console.log(genRanHex(3));
Run Code Online (Sandbox Code Playgroud)


  1. 传入一个数字 ( size) 作为返回字符串的长度。

  2. 定义一个空数组 ( result) 和一个在[0-9]和[a-f]( hexRef)范围内的字符串数组。

  3. 在循环的每次迭代中for,生成一个 0 到 15 的随机数,并将其用作步骤 2 ( hexRef)中字符串数组中值的索引——然后push()是步骤 2 ( result)中空数组的值。

  4. 将数组 ( result) 作为join('')ed 字符串返回。


演示 2

const getRanHex = size => {
  let result = [];
  let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

  for (let n = 0; n < size; n++) {
    result.push(hexRef[Math.floor(Math.random() * 16)]);
  }
  return result.join('');
}

console.log(getRanHex(6));
console.log(getRanHex(12));
console.log(getRanHex(3));
Run Code Online (Sandbox Code Playgroud)


Ice*_*unk 9

有几种方法。一种方法是从预定义的字符串中提取:

function genHexString(len) {
    const hex = '0123456789ABCDEF';
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += hex.charAt(Math.floor(Math.random() * hex.length));
    }
    return output;
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是附加一个 0 到 15 之间的随机数,并使用 toString 转换为十六进制:

function genHexString(len) {
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += (Math.floor(Math.random() * 16)).toString(16);
    }
    return output;
}
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以使用十六进制数字 0xfffff 来随机生成十六进制字符串

getHexaNumb() {
    return Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")
}

Run Code Online (Sandbox Code Playgroud)


Kan*_*dan 5

This securely generates a 32-byte random string and encodes it as hex (64 characters).

Array.from(crypto.getRandomValues(new Uint8Array(32)))
    .map(b => b.toString(16).padStart(2, '0')).join('');
Run Code Online (Sandbox Code Playgroud)

Long version:

function generateRandomHexString(numBytes) {
    const bytes = crypto.getRandomValues(new Uint8Array(numBytes));
    const array = Array.from(bytes);
    const hexPairs = array.map(b => b.toString(16).padStart(2, '0'));
    return hexPairs.join('')
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*isi 1

如果您可以使用 lodash 库,这里是生成 16 个字符字符串的代码片段:

let randomString = _.times(16, () => (Math.random()*0xF<<0).toString(16)).join('');
Run Code Online (Sandbox Code Playgroud)