I have a function that accepts a number which will convert it to a 5x7 graphic representation of digits like this:
Console.WriteLine(" ███ "); // byte: 0000 1110
Console.WriteLine("█ █"); // 0001 0001
Console.WriteLine("█ █"); // 0001 0001
Console.WriteLine("█ █"); // 0001 0001
Console.WriteLine("█ █"); // 0001 0001
Console.WriteLine("█ █"); // 0001 0001
Console.WriteLine(" ███ "); // 0000 1110
I was told it can be done faster using byte arrays. This is basically what I did:
byte[] data = new byte[] { 14, 17, 17, 17, 17, 17, 14 };
BitArray bitData = new BitArray(data);
int bitCounter = 0;
foreach (bool bit in bitData)
{
if (bit)
Console.Write("█");
else
Console.Write(" ");
bitCounter++;
if (bitCounter>7)
{
bitCounter=0;
Console.WriteLine();
}
}
This is slower than what is started with so I can't use it. Can anyone show me a better way?
Update: StringBuilder does help, but it will be a bit slower than the original code I had. Its still basically using the write command 7 times in the console is slowing me down. I tried using using just 1 write command using \\n, but I need to indent the next line without erasing inside the indented spaces.
I Minimized IO. Here is a version below that makes console calls only at the end.
var stringBuilder = new StringBuilder();
bitCounter = 0;
foreach (bool bit in bitData)
{
if (bit)
stringBuilder.Append("█");
else
stringBuilder.Append(" ");
bitCounter++;
if (bitCounter > 7)
{
bitCounter = 0;
Console.WriteLine(stringBuilder.ToString());
stringBuilder.Clear();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.