在JavaScript中,您可以将数字转换为具有特定radix的字符串表示形式,如下所示:
(12345).toString(36) // "9ix"
...你可以将它转换回这样的常规数字:
parseInt("9ix", 36) // 12345
36是您可以指定的最高基数。它显然使用字符0-9
和a-z
作为数字(总共36个)。
我的问题:将数字转换为基数为64的表示的最快方式是什么(例如,使用A-Z
,-
和_
表示额外的28位数?)< / p>
更新:有四个人发布了回复,说这个问题是重复的,或者我正在寻找Base64。我不是。
“Base64”是一种在简单的ASCII字符集中编码二进制数据的方法,使其可以安全地通过网络传输等(因此纯文本系统不会使二进制文件乱码)。
这不是我要问的问题。我要求将数字转换为基数64字符串表示。 (JavaScript toString(radix)
会自动为最高36的任何基数执行此操作;我需要一个自定义函数来获取基数64.)
更新2 :以下是一些输入&amp;输出示例......
0 → "0"
1 → "1"
9 → "9"
10 → "a"
35 → "z"
61 → "Z"
62 → "-"
63 → "_"
64 → "10"
65 → "11"
128 → "20"
etc.
答案 0 :(得分:46)
以下是NUMBERS解决方案的草图(不是字节数组:)
仅针对正数,忽略小数部分,而不是真正测试 - 只是草图!
Base64 = {
_Rixits :
// 0 8 16 24 32 40 48 56 63
// v v v v v v v v v
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/",
// You have the freedom, here, to choose the glyphs you want for
// representing your base-64 numbers. The ASCII encoding guys usually
// choose a set of glyphs beginning with ABCD..., but, looking at
// your update #2, I deduce that you want glyphs beginning with
// 0123..., which is a fine choice and aligns the first ten numbers
// in base 64 with the first ten numbers in decimal.
// This cannot handle negative numbers and only works on the
// integer part, discarding the fractional part.
// Doing better means deciding on whether you're just representing
// the subset of javascript numbers of twos-complement 32-bit integers
// or going with base-64 representations for the bit pattern of the
// underlying IEEE floating-point number, or representing the mantissae
// and exponents separately, or some other possibility. For now, bail
fromNumber : function(number) {
if (isNaN(Number(number)) || number === null ||
number === Number.POSITIVE_INFINITY)
throw "The input is not valid";
if (number < 0)
throw "Can't represent negative numbers now";
var rixit; // like 'digit', only in some non-decimal radix
var residual = Math.floor(number);
var result = '';
while (true) {
rixit = residual % 64
// console.log("rixit : " + rixit);
// console.log("result before : " + result);
result = this._Rixits.charAt(rixit) + result;
// console.log("result after : " + result);
// console.log("residual before : " + residual);
residual = Math.floor(residual / 64);
// console.log("residual after : " + residual);
if (residual == 0)
break;
}
return result;
},
toNumber : function(rixits) {
var result = 0;
// console.log("rixits : " + rixits);
// console.log("rixits.split('') : " + rixits.split(''));
rixits = rixits.split('');
for (var e = 0; e < rixits.length; e++) {
// console.log("_Rixits.indexOf(" + rixits[e] + ") : " +
// this._Rixits.indexOf(rixits[e]));
// console.log("result before : " + result);
result = (result * 64) + this._Rixits.indexOf(rixits[e]);
// console.log("result after : " + result);
}
return result;
}
}
更新:这是上面的一些(非常轻量级)测试,用于在您拥有console.log的NodeJ中运行。
function testBase64(x) {
console.log("My number is " + x);
var g = Base64.fromNumber(x);
console.log("My base-64 representation is " + g);
var h = Base64.toNumber(g);
console.log("Returning from base-64, I get " + h);
if (h !== Math.floor(x))
throw "TEST FAILED";
}
testBase64(0);
try {
testBase64(-1);
}
catch (err) {
console.log("caught >>>>>> " + err);
}
try {
testBase64(undefined);
}
catch (err) {
console.log("caught >>>>>> " + err);
}
try {
testBase64(null);
}
catch (err) {
console.log("caught >>>>>> " + err);
}
try {
testBase64(Number.NaN);
}
catch (err) {
console.log("caught >>>>>> " + err);
}
try {
testBase64(Number.POSITIVE_INFINITY);
}
catch (err) {
console.log("caught >>>>>> " + err);
}
try {
testBase64(Number.NEGATIVE_INFINITY);
}
catch (err) {
console.log("caught >>>>>> " + err);
}
for(i=0; i<100; i++)
testBase64(Math.random()*1e14);
答案 1 :(得分:15)
这是一个仅适用于32位整数的版本,即-2147483648和2147483647(含)之间的任何数字。
我在Reb Cabin的顶部答案中修改了版本。这应该快得多,因为它使用位操作和查找表。
Base64 = (function () {
var digitsStr =
// 0 8 16 24 32 40 48 56 63
// v v v v v v v v v
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-";
var digits = digitsStr.split('');
var digitsMap = {};
for (var i = 0; i < digits.length; i++) {
digitsMap[digits[i]] = i;
}
return {
fromInt: function(int32) {
var result = '';
while (true) {
result = digits[int32 & 0x3f] + result;
int32 >>>= 6;
if (int32 === 0)
break;
}
return result;
},
toInt: function(digitsStr) {
var result = 0;
var digits = digitsStr.split('');
for (var i = 0; i < digits.length; i++) {
result = (result << 6) + digitsMap[digits[i]];
}
return result;
}
};
})();
例如,
Base64.fromInt(-2147483648); // gives "200000"
Base64.toInt("200000"); // gives -2147483648
答案 2 :(得分:3)
这是一个不同的看法
function base64(value) {
if (typeof(value) === 'number') {
return base64.getChars(value, '');
}
if (typeof(value) === 'string') {
if (value === '') { return NaN; }
return value.split('').reverse().reduce(function(prev, cur, i) {
return prev + base64.chars.indexOf(cur) * Math.pow(64, i);
}, 0);
}
}
base64.chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
base64.getChars = function(num, res) {
var mod = num % 64,
remaining = Math.floor(num / 64),
chars = base64.chars.charAt(mod) + res;
if (remaining <= 0) { return chars; }
return base64.getChars(remaining, chars);
};
答案 3 :(得分:3)
我一直在寻找同一问题的解决方案,但对于 ActionScript(AS3),很明显许多人将 Base64编码与 <混淆em>'基数为64的数字'(基数为64) 。
绝大多数网站都提供'计算密码术'和非数学的解决方案。作为解决方案,这对我们需要的转换没有用。
在此次咨询之前,我知道方法toString(radix)和parseInt(radix),我使用了Hex数字(基数16)两种颜色和其他功能。
但是,在 AS3 或 JS 中都没有一种用于与基数64进行转换的数值方法。
在来到这个网站之前,我发现:
为避免与加密方法混淆,要使用的方法基于众所周知的名称:
代码是用 AS3 编写的,但非常清楚(与JS一样)。
注意:建议使用数字:1 * 10 16
最后,包括一个例子和操作结果。
const STR64:Array = ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/').split( '' );
// TRANSFORM NUMBERS BETWEEN radix 10 AND radix 64
/** Methods based on answers shared in:
* @url http://stackoverflow.com/questions/6213227/fastest-way-to-convert-a-number-to-radix-64-in-javascript
*/
// METHODS
/** to64String: Method to transform a radix 10 number to radix 64 number (as string)
* @param input Number for transform to radix 64 (as String)
* @param current String data (don't needed in request)
* @return String Number in radix 64 as String;
*
* @based http://stackoverflow.com/users/383780/monocle
* @based base64( Method for number to string - NOT string part )
*/
function to64String( input:Number, current:String = '' ):String
{
if ( input < 0 && current.length == 0 ){
input = input * - 1;
}
var modify:Number = input % 64;
var remain:Number = Math.floor( input / 64 );
var result:String = STR64[ modify ] + current;
return ( remain <= 0 ) ? result : to64String( remain, result );
}
/** to64Parse: Method for transform a number in radix 64 (as string) in radix 10 number
* @param input Number in radix 64 (as String) to transform in radix 10
* @return Number in radix 10
*
* @based http://stackoverflow.com/users/520997/reb-cabin
* @based Base64.toNumber( Method for string to number )
*/
function to64Parse ( input:String ):Number
{
var result:Number = 0;
var toProc:Array = input.split( '' );
var e:String;
for ( e in toProc ){
result = ( result * 64 ) + STR64.indexOf( toProc[ e ] );
}
return result;
}
// TEST
var i:int = 0;
var max:Number = 1000000000000;
var min:Number = 0;
for ( i == 0; i < 20; i++ ){
var num:Number = ( Math.ceil( Math.random() * ( max - min + 1 ) ) + min );
var s64:String = to64String( num );
var ret:Number = to64Parse ( s64 );
trace( i + '\t# ' + num + '\t' + s64 + '\t' + ret + '\t' + ( ret == num ) )
}
// TEST RESULT
/*
0 # 808936734685 LxYYv/d 808936734685 true
1 # 931332556532 NjXvwb0 931332556532 true
2 # 336368837395 E5RJSMT 336368837395 true
3 # 862123347820 Mi6jk9s 862123347820 true
4 # 174279278611 CiT2sAT 174279278611 true
5 # 279361353722 EELO/f6 279361353722 true
6 # 435602995568 GVr9jlw 435602995568 true
7 # 547163526063 H9lfNOv 547163526063 true
8 # 188017380425 CvGtYxJ 188017380425 true
9 # 720098771622 KepO0Km 720098771622 true
10 # 408089106903 F8EAZnX 408089106903 true
11 # 293941423763 ERwRi6T 293941423763 true
12 # 383302396164 Fk+mmkE 383302396164 true
13 # 695998940618 KIMxQXK 695998940618 true
14 # 584515331314 IgX1CTy 584515331314 true
15 # 528965753970 Hso0Nxy 528965753970 true
16 # 5324317143 E9WqHX 5324317143 true
17 # 772389841267 LPWBalz 772389841267 true
18 # 954212692102 N4rgjCG 954212692102 true
19 # 867031893694 MnfIMa+ 867031893694 true
*/
答案 4 :(得分:2)
我为这种类型的操作power-radix编写了一个npm模块,它可以帮到你。您可以使用用户定义的字符编码将任何数字从任何基数转换为任何基数。
例如:
var base = ['Q', 'W', 'E', 'R', 'T', 'Y', 'I', 'O', 'U'];
new PowerRadix([1, 0], 10).toArray(base); // ['W', 'Q']
new PowerRadix('10', 10).toArray(base); // ['W', 'Q']
new PowerRadix(10, 10).toArray(base); // ['W', 'Q']
new PowerRadix([1, 0], 10).toString(base); // "WQ"
new PowerRadix('10', 10).toString(base); // "WQ"
new PowerRadix(10, 10).toString(base); // "WQ"
该模块还支持自定义源基数编码。
new PowerRadix('ba', ['a', 'b']); // base 2 source radix, uses 'a' = 0 & 'b' = 1 character set.
new PowerRadix('ba', ['a', 'b']).toString(10); // returns "2"
答案 5 :(得分:2)
以下实现将正数,负数和非整数转换为任意基数。转换回十进制很容易以类似的方式实现:
function toAnyBase(num, base) {
if (!Number.isInteger(base) || base < 2) throw new RangeError("toAnyBase() base argument must be an integer >= 2");
if (!Number.isFinite(num)) return num.toString();
if (num < 0) return "-" + toAnyBase(-num, base);
const digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#_",
inv_base = 1 / base;
var result = "",
residual;
// Integer part:
residual = Math.trunc(num);
do {
result = digits.charAt(residual % base) + result;
residual = Math.trunc(residual * inv_base);
} while (residual != 0);
// Fractional part:
residual = num % 1;
if (residual != 0) {
result += ".";
var max = 1000;
do {
residual *= base;
result += digits.charAt(Math.trunc(residual));
residual %= 1;
} while (residual != 0 && --max != 0);
}
return result;
}
console.log(toAnyBase( 64, 64)); // "10"
console.log(toAnyBase(-1.5, 64)); // "-1.w"
&#13;
答案 6 :(得分:2)
如果您使用的是NodeJS,则可以使用以下代码:
var base64 = Buffer.from([i>>24,i>>16,i>>8,i]).toString('base64').substr(0,6);
答案 7 :(得分:2)
对所有javascript安全整数范围(从-9007199254740991
到9007199254740991
)的极快实施:
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// binary to string lookup table
const b2s = alphabet.split('');
// string to binary lookup table
// 123 == 'z'.charCodeAt(0) + 1
const s2b = new Array(123);
for (let i = 0; i < alphabet.length; i++) {
s2b[alphabet.charCodeAt(i)] = i;
}
// number to base64
const ntob = (number) => {
if (number < 0) return `-${ntob(-number)}`;
let lo = number >>> 0;
let hi = (number / 4294967296) >>> 0;
let right = '';
while (hi > 0) {
right = b2s[0x3f & lo] + right;
lo >>>= 6;
lo |= (0x3f & hi) << 26;
hi >>>= 6;
}
let left = '';
do {
left = b2s[0x3f & lo] + left;
lo >>>= 6;
} while (lo > 0);
return left + right;
};
// base64 to number
const bton = (base64) => {
let number = 0;
const sign = base64.charAt(0) === '-' ? 1 : 0;
for (let i = sign; i < base64.length; i++) {
number = number * 64 + s2b[base64.charCodeAt(i)];
}
return sign ? -number : number;
};
npm:number-to-base64
答案 8 :(得分:0)
我一直在寻求相同的解决方案,我想我已经用基本的Javascript尽可能少地概括了这个人的想法。应该适用于任何正整数,并且只要所有字符都是唯一的,endex的长度就可以适合任何基数。
var endex = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
function encode(intcode){
if(intcode < endex.length){
return endex[intcode];
}else{
return encode(Math.floor(intcode/endex.length)) + endex[intcode%endex.length];
}
}
function decode(charcode){
if(charcode.length < 2){
return endex.indexOf(charcode);
}else{
return (decode(charcode.slice(0, -1)) * endex.length) + endex.indexOf(charcode.slice(-1));
}
}
答案 9 :(得分:0)
我认为这个问题缺少一个简短的解决方案。
const digit = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
toB64 = x=>x.toString(2).split(/(?=(?:.{6})+(?!.))/g).map(v=>digit[parseInt(v,2)]).join("")
fromB64 = x=>x.split("").reduce((s,v,i)=>s=s*64+digit.indexOf(v),0)
适用于0
和Number.MAX_SAFE_INTEGER
之间的所有整数。
答案 10 :(得分:-1)
好吧,你可以使用任何Javascript Base64库:或许this question回答它?
编辑:二进制数据本质上只是一个字节序列。如果假设字节表示单个数字,则可以将字节序列表示为基本64字符串。对它们进行解码并对字节进行一些简单的数学计算得到一个数字。将数字转换为字节序列并编码以获取字符串。看起来很合理,除非你以某种方式投资于String中使用的特定字符。
答案 11 :(得分:-1)
我知道问题是Java Script,但这里是java的解决方案,你可能很容易转换它。
private String toShortString(BigInteger value, String language) {
StringBuilder stringBuilder = new StringBuilder();
BigInteger length = BigInteger.valueOf(language.length());
while (value.compareTo(BigInteger.ZERO) > 0){
int index = value.mod(length).intValue();
stringBuilder.append(language.charAt(index));
value = value.divide(length);
}
return stringBuilder.reverse().toString();
}
BigInteger value = BigInteger.valueOf(2).pow(128);
System.out.println(value);
System.out.println(value.toString(16));
System.out.println(toShortString(value, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-=_+"));
输出
340282366920938463463374607431768211456
100000000000000000000000000000000个
8hS#phQaCO3849pE + ^ El4
如果您将其转换为Java Script,请编辑此问题并在下面添加。
答案 12 :(得分:-3)
在mozilla或webkit浏览器中,您可以使用btoa()和atob()对base64进行编码和解码。