栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Base32解码

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Base32解码

Frombase32String
在此处找到.NET的此实现检查。


编辑:上面的链接已死;您可以在archive.org上找到存档副本

实际代码如下:

using System;using System.Text;public sealed class base32 {      // the valid chars for the encoding      private static string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP";      /// <summary>      /// Converts an array of bytes to a base32-k string.      /// </summary>      public static string Tobase32String(byte[] bytes) { StringBuilder sb = new StringBuilder();         // holds the base32 chars byte index; int hi = 5; int currentByte = 0; while (currentByte < bytes.Length) {       // do we need to use the next byte?       if (hi > 8) {  // get the last piece from the current byte, shift it to the right  // and increment the byte counter  index = (byte)(bytes[currentByte++] >> (hi - 5));  if (currentByte != bytes.Length) {        // if we are not at the end, get the first piece from        // the next byte, clear it and shift it to the left        index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index);  }  hi -= 3;       } else if(hi == 8) {   index = (byte)(bytes[currentByte++] >> 3);  hi -= 3;        } else {  // simply get the stuff from the current byte  index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);  hi += 5;       }       sb.Append(ValidChars[index]); } return sb.ToString();      }      /// <summary>      /// Converts a base32-k string into an array of bytes.      /// </summary>      /// <exception cref="System.ArgumentException">      /// Input string <paramref name="s">s</paramref> contains invalid base32-k characters.      /// </exception>      public static byte[] Frombase32String(string str) { int numBytes = str.Length * 5 / 8; byte[] bytes = new Byte[numBytes]; // all UPPERCASE chars str = str.ToUpper(); int bit_buffer; int currentCharIndex; int bits_in_buffer; if (str.Length < 3) {       bytes[0] = (byte)(ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);       return bytes; } bit_buffer = (ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5); bits_in_buffer = 10; currentCharIndex = 2; for (int i = 0; i < bytes.Length; i++) {       bytes[i] = (byte)bit_buffer;       bit_buffer >>= 8;       bits_in_buffer -= 8;       while (bits_in_buffer < 8 && currentCharIndex < str.Length) {  bit_buffer |= ValidChars.IndexOf(str[currentCharIndex++]) << bits_in_buffer;  bits_in_buffer += 5;       } } return bytes;      }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/411883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号