如何将整数转换为JavaScript中指定字符集的字符串 [英] How to change an integer into a string with specified character set in JavaScript

查看:81
本文介绍了如何将整数转换为JavaScript中指定字符集的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个基于散列函数输出的整数输入 var i = 1234567890 ,我需要创建一个缩写的,区分大小写的字母数字字符串。这是为了使用带有区分大小写的散列参数的短URL,例如 http://example.com/?hash=1M0nlPk



JavaScript的 i.toString(36)会使用字符0-9和az。这是解决方案的一部分。但是,我需要对未知或可配置长度的字符集进行操作,例如 012abcABC 。我怎样才能将int转换为只包含这个字符集的字符串?



更新:我已经改进了这个问题的措辞。它不是最快的转换方式一个数字是64的JavaScript?,因为字符集是任意的。这个问题中的一些答案可能适用于这个问题,但我相信这是一个根本不同的问题。

解决方案

这是base64库可以回答的Base64转换问题的变体。但是,这些库对于这个问题可能是矫枉过正,所以下面是基于简单& @ Reb.Cabin优雅的解决方案。在这段回复中,通常用于创建诅咒词的元音和各种问题字母是删除,所以随机整数哈希不会创建一个攻击性的短URL。



data-console =falsedata-babel =false>


Given an integer input var i = 1234567890 based on the output of a hash function, I need to create a shortened, case sensitive alphanumeric string. This is for purposes of having a short URL with a case-sensitive hashed parameter such as http://example.com/?hash=1M0nlPk.

JavaScript's i.toString(36) would use characters 0-9 and a-z. That's part of the way to a solution. However, I need to operate on a character set of unknown or configureable length, e.g. 012abcABC. How could I convert an int to a string consisting only of this character set?

UPDATE: I have improved the wording of this question. It is not a duplicate of Fastest way to convert a number to radix 64 in JavaScript? because the character set is arbitrary. Some of the answers in that question may be adaptable to this question, but I believe it to be a fundamentally different question.

解决方案

This is a variant of a "Base64" conversion question that can be answered by "base n" libraries. However, these libraries may be "overkill" for this question, so below is modified code based on a simple & elegant solution by @Reb.Cabin. Credit also to editors @callum, @Philip Kaplan, @Oka on this code.

In this response, vowels and various "problem letters" commonly used to create curse words are removed, so a random integer hash will not create an offensive short URL.

// Based on Base64 code by @Reb.Cabin, edits by @callum, @philip Kaplan, @Oka available at https://stackoverflow.com/a/6573119/3232832
BaseN = {
    _Rixits :
//   0       8       16      24      32      40      48      56     63
//   v       v       v       v       v       v       v       v      v
    "0123456789BDGHJKLMNPQRTVWXYZbdghjklmnpqrtvwxyz-_",
//  original base64
//  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_",
    // You have the freedom, here, to choose the glyphs you want for 
    // representing your base-64 numbers.
    // This cannot handle negative numbers and only works on the 
    //     integer part, discarding the fractional part.
    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 = '';
        var rixitLen = this._Rixits.length;
        while (true) {
            rixit = residual % rixitLen;
            result = this._Rixits.charAt(rixit) + result;
            residual = Math.floor(residual / rixitLen);

            if (residual === 0)
                break;
            }
        return result;
    },

    toNumber : function(rixits) {
        var result = 0;
        for (var e = 0; e < rixits.length; e++) {
            result = (result * this._Rixits.length) + this._Rixits.indexOf(rixits[e]);
        }
        return result;
    }
};

var i = 1234567890;
var encoded = BaseN.fromNumber(1234567890);
var decoded = BaseN.toNumber(encoded);
document.writeln('Given character set "' + BaseN._Rixits + '", the number ' + i + ' is encoded to ' + encoded + ' then back again to ' + decoded + '.');

这篇关于如何将整数转换为JavaScript中指定字符集的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆