将字节数组转换成任何基数 [英] Convert byte array into any base

查看:284
本文介绍了将字节数组转换成任何基数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组(任意长度),我想使用我自己的基编码器把这个数组编码成字符串。在 .NET 是标准的 Base64 编码器,但如果我想在 Base62 Base53 Base13



甚至可以创建这样的通用基编码器?



我知道我可以用简单的方法来做,也就是说,对于每个字节的保留固定数量chars(在 Base62 的情况下,这将是5个字符),并执行直接的byte-> chars编码,但我会浪费空间,作为5 Base62 chars可以包含超过1个字节,但不超过2个字节。



我该如何编写这样的编码器?还是有一些类吗?

请注意,我还需要通用解码器,否则这对我来说是无用的。



资源



由于解决方案已知(使用 BigInteger ),我只想在这里放置一些与 BigInteger class,因为它在.NET 3.5中不可用:



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/BigInt eger_Library.aspx

http:// www。 codeproject.com/KB/cs/biginteger.aspx

解决方案

如果性能不是问题,请使用<背景中的一个href =http://msdn.microsoft.com/en-us/library/system.numerics.biginteger_members.aspx =nofollow noreferrer> 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.

这篇关于将字节数组转换成任何基数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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