挑战:将图像文件的“修改日期”DateTime转换为适合于在url中保持唯一性的版本号/字符串,因此图像的每次修改都会生成一个唯一的url,版本号/字符串尽可能短。
代码的短小性仅次于数字/字符串的短小,如果这并不真正符合代码-高尔夫状态:-)
要求
编辑:这不是完全的理论/难题,所以我想我宁愿把它留在这里,而不是在代码-高尔夫堆栈交换?
发布于 2011-09-12 03:36:59
使用DateTime.Ticks属性,然后将其转换为36基数。它将非常短,并可用于一个URL。
下面是一个转换到/从Base 36的类:
http://www.codeproject.com/KB/cs/base36.aspx
您也可以使用基数62,但不能使用base64,因为除了数字和字母之外,基数64中的一个额外数字是+,它需要进行url编码,并且您说您希望避免这样做。
发布于 2011-09-13 04:07:01
好的,把答案和评论结合起来,我想出了以下几点。
注意:删除零填充字节,并从项目开始时的启动日期差异,以减少数字的大小。
public static string GetVersion(DateTime dateTime)
{
System.TimeSpan timeDifference = dateTime - new DateTime(2010, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long min = System.Convert.ToInt64(timeDifference.TotalMinutes);
return EncodeTo64Url(min);
}
public static string EncodeTo64Url(long toEncode)
{
string returnValue = EncodeTo64(toEncode);
// returnValue is base64 = may contain a-z, A-Z, 0-9, +, /, and =.
// the = at the end is just a filler, can remove
// then convert the + and / to "base64url" equivalent
//
returnValue = returnValue.TrimEnd(new char[] { '=' });
returnValue = returnValue.Replace("+", "-");
returnValue = returnValue.Replace("/", "_");
return returnValue;
}
public static string EncodeTo64(long toEncode)
{
byte[] toEncodeAsBytes = System.BitConverter.GetBytes(toEncode);
if (BitConverter.IsLittleEndian)
Array.Reverse(toEncodeAsBytes);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes.SkipWhile(b=>b==0).ToArray());
return returnValue;
}https://stackoverflow.com/questions/7383021
复制相似问题