如何将两个Base58转HEX的JavaScript脚本合并为一个
合并后的Base58转HEX脚本(无需文件中转)
直接通过变量传递解码后的字节数组,省去文件读写步骤,完整代码如下:
// Base58字符集(适配比特币系测试网/主网私钥编码) const BASE58_CHARS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; // Base58解码为字节数组 function base58Decode(str) { let result = new Uint8Array(32); // 私钥固定32字节长度 let resultIndex = result.length - 1; for (const char of str) { const charValue = BASE58_CHARS.indexOf(char); if (charValue === -1) throw new Error('包含无效Base58字符'); // 大数进位运算,模拟Base58解码逻辑 let carry = charValue; for (let i = result.length - 1; i >= 0; i--) { const product = result[i] * 58 + carry; result[i] = product & 0xff; carry = product >> 8; } if (carry !== 0) throw new Error('Base58字符串长度超过私钥范围'); } // 移除前导零(对应Base58的前导"1") while (resultIndex > 0 && result[resultIndex] === 0) { resultIndex--; } return result.slice(resultIndex); } // 字节数组转HEX字符串 function bytesToHex(bytes) { return Array.from(bytes) .map(byte => byte.toString(16).padStart(2, '0')) .join(''); } // 主逻辑:替换成你的测试网私钥 const testPrivateKey = '这里填你的无资金测试Base58私钥'; const decodedBytes = base58Decode(testPrivateKey); const hexKey = bytesToHex(decodedBytes); console.log('转换后的HEX私钥:', hexKey);
使用说明
- 把
testPrivateKey变量里的字符串替换成你自己的测试网Base58私钥 - 用Node.js运行脚本,或者直接复制到浏览器开发者控制台(F12打开)执行,就能看到HEX结果
合并逻辑说明
原来的两个脚本是把解码后的字节数组写入文件,再读取文件转HEX。现在直接将base58Decode返回的字节数组作为参数传给bytesToHex函数,全程在内存里完成转换,不需要文件中转。
注意点
- 这个脚本专门针对32字节的比特币系私钥(测试网/主网私钥都是这个长度),如果是其他类型的Base58数据,需要调整
result数组的初始长度 - 你用的是无资金测试私钥,不用担心安全问题,放心测试
内容的提问来源于stack exchange,提问作者Gil
相关产品推荐
相关产品推荐

