如何生成一个指定长度、仅由十六进制字符(0123456789abcdef)组成的随机字符串?
这适用于长度最多为13:
randomHex = length => (
'0'.repeat(length)
+ Math.floor((Math.random() * 16 ** length))
.toString(16)
).slice(-length);
console.log(randomHex(4));
console.log(randomHex(6));
console.log(randomHex(13));
console.log(randomHex(20));
从一个 Math.random() 调用中可以快速获取最多 7 个字符 (A):
const halfBytesIn35 = 7 // = 3.5 bytes
const byte35 = Math.pow(16, halfBytesIn35)
const bytes35 = () => ((Math.random() * byte35) | 0).toString(16).padStart(halfBytesIn35,'0')
console.log('A: ' + bytes35())
const bytes65 = len => Math.floor(Math.random() * Math.pow(16, len*2)).toString(16).padStart(len,'0')
console.log('B: ' + bytes65(6))
function moreBytes (len) {
len *= 2; // alternative: len <<= 1 if you do not use half bytes. This might allow optimizations based on len always being an Integer then.
let builder = "";
while (len > 0) {
builder += bytes35()
len -= 7
}
return builder.slice(0,len)
}
console.log('C: ' + moreBytes(16))
如果您计划频繁使用,请存储Math.pow常量。
第8个字母会溢出到二进制底数的符号位。
通过使用Math.floor(B)甚至循环生成器以获得任意长度(C),您可以从一个调用中达到13个字符。
请注意,这可能被用于定义过早的优化。如果您的瓶颈确实是随机数的创建,请考虑使用LUTs。如果您正在开发嵌入式系统,则这很常见。(在这种情况下,不得不使用javascript,但没有时间预算来生成随机数)
你可以使用我在这里编写的函数轻松生成一个6位十六进制代码
function generateRandomHex(){
let result = '';
const characters = 'ABCDEF123456789';
const charactersLength = characters.length;
for (let i = 0; i < 6; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function generateRandomHex(length){
let result = '';
const characters = 'ABCDEF123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
const makeSize = 2
const uniqueHexValue = [...Array(makeSize)].map(() => Math.floor(Math.random() * new Date().valueOf()).toString(16)).join("")
这是一个生成随机十六进制颜色代码的简化程序:
let items = ["a", "b", "c", "d", "e", "f"];
let item = items[Math.floor(Math.random() * items.length)];
console.log(item);
let random = Math.random().toString().slice(2, 6);
console.log(`#${item}${random}${item}`);
function genHexString(len) {
const str = Math.floor(Math.random() * Math.pow(16, len)).toString(16);
return "0".repeat(len - str.length) + str;
}
通过使用 Math.random,您可以方便地一次生成 13 个字符。如果您想要一个任意长度的字符串,您仍然可以使用“一行代码”来实现:
const makeRandomHexString = (length: number) =>
Array.from({ length: Math.ceil(length / 13) })
.map(() =>
Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2))
.toString(16)
.padStart(13, '0')
)
.join('')
.substring(0, length);
aAbBfF
是有效的吗?另外,是“普通”的随机还是加密强度的随机? - georg