Shortest string representation for Int32
I need to convert an Int32
to a code that has to be entered on a web form. To keep it simple for the visitors, this code needs to be as simple and short as possible.
Does anybody know a good algorithm for converting an Int32
to the shortest string representation possi开发者_JAVA百科ble using only [0-9] and [A-Z]?
You could encode to base-36, but for everyone's sanity (not least your users, dealing with I vs 1, O vs 0 etc), I suggest just sticking to hex; plus it is built in:
int value = 22334;
string hex = Convert.ToString(value, 16); // 573e
value = Convert.ToInt32(hex, 16);
A base 36 representation is what you want. This uses both alphabetical and numerical symbols to encode numbers, for a very compact representation.
Just an example, I haven't looked up all the details for this.
Given a 32 bit int:
Split it into 8x4 bits
A 4 bit array gives 2^4 = 16 possible combos
Then match each literal value of the 4 bits to the ascii character code starting from lowercase A or whatever.
string s = code.ToString();
You can use the Encoding class to get the string:
int value = 1234;
string intString = Encoding.Default.GetString(BitConverter.GetBytes(value));
Instead of the Default encoding you can choose whichever you want.
You have a few options:
- Base36 meets your stated requirements
- Base64 is shorter but you have the issue of escaping the final ='s
One fundamental problem you have is that the shorter you make it, the harder it is to remember correctly. So you need to think about whether you want this to be for copy/paste or for people to remember.
For copy/paste, I would probably go with aligned base64 given so as to avoid the equals on the end (but you could change = to _ and convert back on the server).
For human-readable, would suggest doing something else altogether.
精彩评论