gpt4 book ai didi

c# - Base32解码

转载 作者:IT王子 更新时间:2023-10-29 04:09:58 26 4
gpt4 key购买 nike

我有一个 base32 字符串,我需要将其转换为字节数组。而且我在 .NET 框架中找不到转换方法时遇到了麻烦。我可以找到 base64 的方法,但找不到 base32 的方法。

Convert.FromBase64String – 像这样的 base32 就完美了。

框架中有这样的方法还是我必须自己滚?

最佳答案

我需要一个 base32 编码器/解码器,所以今天下午我花了几个小时把它放在一起。我相信它符合此处列出的标准:https://www.rfc-editor.org/rfc/rfc4648#section-6 .

public class Base32Encoding
{
public static byte[] ToBytes(string input)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentNullException("input");
}

input = input.TrimEnd('='); //remove padding characters
int byteCount = input.Length * 5 / 8; //this must be TRUNCATED
byte[] returnArray = new byte[byteCount];

byte curByte = 0, bitsRemaining = 8;
int mask = 0, arrayIndex = 0;

foreach (char c in input)
{
int cValue = CharToValue(c);

if (bitsRemaining > 5)
{
mask = cValue << (bitsRemaining - 5);
curByte = (byte)(curByte | mask);
bitsRemaining -= 5;
}
else
{
mask = cValue >> (5 - bitsRemaining);
curByte = (byte)(curByte | mask);
returnArray[arrayIndex++] = curByte;
curByte = (byte)(cValue << (3 + bitsRemaining));
bitsRemaining += 3;
}
}

//if we didn't end with a full byte
if (arrayIndex != byteCount)
{
returnArray[arrayIndex] = curByte;
}

return returnArray;
}

public static string ToString(byte[] input)
{
if (input == null || input.Length == 0)
{
throw new ArgumentNullException("input");
}

int charCount = (int)Math.Ceiling(input.Length / 5d) * 8;
char[] returnArray = new char[charCount];

byte nextChar = 0, bitsRemaining = 5;
int arrayIndex = 0;

foreach (byte b in input)
{
nextChar = (byte)(nextChar | (b >> (8 - bitsRemaining)));
returnArray[arrayIndex++] = ValueToChar(nextChar);

if (bitsRemaining < 4)
{
nextChar = (byte)((b >> (3 - bitsRemaining)) & 31);
returnArray[arrayIndex++] = ValueToChar(nextChar);
bitsRemaining += 5;
}

bitsRemaining -= 3;
nextChar = (byte)((b << bitsRemaining) & 31);
}

//if we didn't end with a full char
if (arrayIndex != charCount)
{
returnArray[arrayIndex++] = ValueToChar(nextChar);
while (arrayIndex != charCount) returnArray[arrayIndex++] = '='; //padding
}

return new string(returnArray);
}

private static int CharToValue(char c)
{
int value = (int)c;

//65-90 == uppercase letters
if (value < 91 && value > 64)
{
return value - 65;
}
//50-55 == numbers 2-7
if (value < 56 && value > 49)
{
return value - 24;
}
//97-122 == lowercase letters
if (value < 123 && value > 96)
{
return value - 97;
}

throw new ArgumentException("Character is not a Base32 character.", "c");
}

private static char ValueToChar(byte b)
{
if (b < 26)
{
return (char)(b + 65);
}

if (b < 32)
{
return (char)(b + 24);
}

throw new ArgumentException("Byte is not a value Base32 value.", "b");
}

}

关于c# - Base32解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/641361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com