I'm taking in a string of input from the command line, and when prefixed by 0o
or 8#
interpreting it as an octal string. I'd like to convert it to a byte array more directly, but I'm not sure how to perform the bit carrying in LINQ.
All three of these methods are fully working; you can checkout the repository or just download the built executable and run it from the command line if need be.
I'd like a review of all three working methods, but more specifically I'd like to have the Octal method, below, not use a BitArray
intermediary, similar to the Binary and Hex methods.
Here's how I'm doing it for hexadecimal (mostly LINQ):
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();
}
And here's binary (mostly LINQ):
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();
}
And here's what I've got for Octal (LINQ, then a BitArray
, then more LINQ):
public static byte[] GetOctalBytes(this string octal, bool preTrimmed = false)
{
if (!preTrimmed)
{
octal = octal.Trim();
if (octal.StartsWith("0o", StringComparison.OrdinalIgnoreCase) || octal.StartsWith("8#"))
octal = octal.Substring(2);
}
octal = octal.TrimStart('0');
if (octal.Length == 0)
octal = "0";
BitArray bits = new BitArray(octal
.Reverse()
.SelectMany(x =>
{
byte value = (byte)(x - '0');
return new bool[] { (value & 0x01) == 1, (value & 0x02) == 2, (value & 0x04) == 4 };
})
.ToArray());
byte[] bytes = new byte[bits.Length / 8 + 1];
bits.CopyTo(bytes, 0);
bytes = bytes.Reverse().SkipWhile(b => b == 0x00).ToArray();
if (bytes.Length == 0)
bytes = new byte[] { 0x00 };
return bytes;
}
I don't like using the BitArray
intermediary, but I don't know how to do it without it. If possible, I'd like the whole conversion in a single LINQ statement like the hex and binary.
This is part of a C# console application for computing hashes. Here's a link to the relevant source file on Github.