寻找一种方法来在C#中的base36序列 [英] Looking for a way to have a base36 sequence in C#

查看:444
本文介绍了寻找一种方法来在C#中的base36序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序使用的序列。这些被存储在Azure的表存储为字符串。要更新获得最新的数字作为一个字符串序列,转换为数字,增加的数量和它存回作为当前序列值。该序列被内部使用的唯一密钥,但他们也是在URL中对用户可见的,所以我想保持简短。

In my application I use sequences. These are stored in Azure table storage as strings. To update the sequence I get the latest number as a string, convert to a number, add to the number and store it back as the current sequence value. The sequences are used internally as unique keys but they are also visible in URLs to the user so I would like to keep them short.

我正在考虑是具有base36序列的想法。换句话说0 - Z。没有人有任何想法我怎么可以得到存储为一个4位数字是以0000,然后添加一个到它给0001,一直到ZZZZ作为序列的最后一个可能值的序列。

What I am considering is the idea of having a sequence in base36. In other words 0-Z. Does anyone have any idea how I can get a sequence that is stored as a 4 digit string starting with "0000" and then add one to it to give "0001" right through to "ZZZZ" as the last possible value of the sequence.

推荐答案

这应该做到这一点:

public static string Inc(string s){

    System.Func<char,int> v = c => (int)((c<='9')?(c-'0'):(c-'A'+10));
    System.Func<int,char> ch = d => (char)(d+((d<10)?'0':('A'-10)));    

    s = s.ToUpper();    
    var sb = new System.Text.StringBuilder(s.Length);
    sb.Length = s.Length;

    int carry = 1;
    for(int i=s.Length-1; i>=0; i--){
        int x = v(s[i])+carry;    
        carry = x/36;
        sb[i] = ch(x%36);
    }
    if (carry>0)
        return ch(carry) + sb.ToString();
    else
        return sb.ToString();
}

这篇关于寻找一种方法来在C#中的base36序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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