我希望您能翻译一个长度可变的字符串输入,将其数值化并解析为字节数组,同时不对其长度施加任何限制。我已经完成了二进制和十六进制的部分:
public static byte[] GetHexBytes(this string hex, bool preTrimmed = false)
{
if (!preTrimmed)
{
hex = hex.Trim();
if (hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
hex = hex.Substring(2);
else if (hex.StartsWith("16#"))
hex = hex.Substring(3);
}
if (hex.Length % 2 != 0) hex = hex.PadLeft(hex.Length + 1, '0');
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static byte[] GetBinaryBytes(this string binary, bool preTrimmed = false)
{
if (!preTrimmed)
{
binary = binary.Trim();
if (binary.StartsWith("0b", StringComparison.OrdinalIgnoreCase) || binary.StartsWith("2#"))
binary = binary.Substring(2);
}
if (binary.Length % 8 != 0) binary = binary.PadLeft(binary.Length + 8 - binary.Length % 8, '0');
return Enumerable.Range(0, binary.Length)
.Where(x => x % 8 == 0)
.Select(x => Convert.ToByte(binary.Substring(x, 8), 2))
.ToArray();
}
public static byte[] GetDecimalBytes(this string dec, bool preTrimmed = false)
{
if (!preTrimmed)
{
dec = dec.Trim();
if (dec.StartsWith("10#"))
dec = dec.Substring(3);
}
//???
}
是否可能以类似于十六进制和二进制版本的方式(从字符串开头开始,向前工作)进行正向转换?
如果不行,是否可以倒序工作,而不对字符串长度施加任何限制,而且不使用System.Numerics或BigInteger之类的东西(手动从字符串中执行)?
我希望它能处理任何字符串长度,最大字符串长度为C#(1,073,741,823)。
示例
"FF".GetHexBytes() => [ 0xFF ]
"11111111".GetBinaryBytes() => [ 0xFF ]
"255".GetDecimalBytes() => [ 0xFF ]
"FFFF".GetHexBytes() => [ 0xFF, 0xFF ]
"1111111111111111".GetBinaryBytes() => [ 0xFF, 0xFF ]
"65535".GetDecimalBytes() => [ 0xFF, 0xFF ]
byte[] byteKey = System.Text.ASCIIEncoding.ASCII.GetBytes("yourString")
。 - Zippy"0xFFFFFFFF".GetHexBytes() == "4294967295".GetDecimalBytes()
,因为0xFFFFFFFF == 4294967295
。这自然而然地扩展到其他值。这个印象是正确的吗? - user743382BigInteger
在内部以非常接近所需格式的格式存储值。只需要进行最小的更改即可提取数字解析以使用byte
数组而不是uint
数组。 - user743382