根据base64的原理,它占用的字符数一定是4的整数。不够4字符的,用=来填充。请写一个算法。
.net code
class TestString
{
public string Fill(string str)
{
return string.Format("{0}{1}", str, "=".Multi((uint)(4 - str.Length % 4)%4));
}
}
static class StringExtends
{
public static string Multi(this string self, uint n)
{
if (n == 0)
return string.Empty;
if (n>255)
throw new ArgumentException("n is too big");
if (n == 1)
return self;
if (n == 2)
return self + self;
if (n == 3)
return self + self + self;
if (n == 4)
return self + self + self + self;
var sb = new StringBuilder();
for (int i=0;i<n;++i)
{
sb.Append(self);
}
return sb.ToString();
}
}
python code
def fill(base64):
return base64 + "="*((4-len(base64)%4)%4)
网友评论