问题描述
我有一个字节数组(任意长度),我想使用我自己的基编码器把这个数组编码成字符串。在 .NET
是标准的 Base64
编码器,但如果我想在 Base62
, Base53
或 Base13
? 甚至可以创建这样的通用基编码器?
我知道我可以用简单的方法来做,也就是说,对于每个字节的保留固定数量chars(在 Base62
的情况下,这将是5个字符),并执行直接的byte-> chars编码,但我会浪费空间,作为5 Base62
chars可以包含超过1个字节,但不超过2个字节。
我该如何编写这样的编码器?还是有一些类吗?
请注意,我还需要通用解码器,否则这对我来说是无用的。
资源
由于解决方案已知(使用 BigInteger
),我只想在这里放置一些与 BigInteger
class,因为它在.NET 3.5中不可用:
如果性能不是问题,请使用 BigInteger 类。你有一个BigInteger的构造函数,它使用字节数组,然后可以手动运行除法和模数循环,以获得其他非标准基础的表示。
看看。
I have an array of bytes (any length), and I want to encode this array into string using my own base encoder. In .NET
is standard Base64
encoder, but what if I want to encode the array in Base62
, Base53
or Base13
?
Is it even possible to create such universal base encoder?
I know I could do it the simple way, that is, for each byte reserve fixed number of chars (in case of Base62
, that would be 5 chars), and do direct byte->chars encoding, but I would be wasting space, as 5 Base62
chars are able to contain more than 1 byte, but less than 2 bytes.
How should I write such an encoder? Or is there already some class for this?
And please note that I need universal decoder as well, otherwise this is useless to me.
Resources
As the solution is already known (use BigInteger
), I would just like to put here some resources relating the BigInteger
class, as it is not available in .NET 3.5:
Big integers in C#
http://intx.codeplex.com/
https://svn.apache.org/repos/asf/incubator/heraldry/libraries/csharp/openid/trunk/Mono/Mono.Math/BigInteger.cs
http://www.codeproject.com/KB/cs/BigInteger_Library.aspx
http://www.codeproject.com/KB/cs/biginteger.aspx
If performance is not an issue, use the BigInteger class in the background. You have a constructor for BigInteger that takes byte array, and you can then manually run loops of division and modulus to get the representation in other non-standard bases.
Also take a look at this.
这篇关于将字节数组转换成任何基数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!