Convert decimal numbers to any base (C#)

You can use this little function to convert a decimal to any base. I use it for compacting large numbers.

public static class BaseConverter
{
    public static string Encode(BigInteger value, int @base=0, string chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    {
        if (@base <= 0) @base = chars.Length;
        var sb = new StringBuilder();
        do
        {
            int m = (int)(value % @base);
            sb.Insert(0, chars[m]);
            value = (value - m) / @base;
        } while (value > 0);
        return sb.ToString();
    }
}

Or you can use it to make a nice GUID:

private static BigInteger UnsignedBigInt(byte[] bytes)
{
    if ((bytes[bytes.Length - 1] & 0x80) != 0) Array.Resize(ref bytes, bytes.Length + 1);
    return new BigInteger(bytes);
}

private static string GetUniqueFileName(string extension)
{
    return BaseConverter.Encode(UnsignedBigInt(Guid.NewGuid().ToByteArray()), 0, "0123456789abcdefghijklmnopqrstuvwxyz_-") + extension;
}
Posted in

Microphone Boost

This post is a bit a different than my usual posts.

I was on Skype, about to start a gaming session with my friend, when he notified me that my mic was really quiet compared to when he talked to his other friends. I checked my settings, everything was maxed out in both Skype and Windows Sound settings.

He told me about this “microphone boost” option that he used before, but I didn’t seem to have it. I thought maybe my driver was out of date?

I tried updating my driver via Windows Devices to no avail, so I tried looking for one from my hardware vendor. Problem is, I couldn’t remember who made my hardware, and I didn’t feel like popping open my computer.

I’ve used a program to give me my device information in the past, but I also couldn’t remember what it was called. I found a new one called HWiNFO which seems to do a pretty good job though. It looks like this:

From here I could see my motherboard was an Asus Sabertooth 55i. Googling “asus sabertooth 55i drivers” lead me to the driver I needed. Get the audio driver.

Unless of course, you have a dedicated sound card. Then grab the driver for that instead! I had one before, but I didn’t feel the need to plug it in for my new rig.

After installing the driver (and a mandatory reboot), I found this ugly guy on my desktop:

Doesn’t have a lot of settings (that I can see), but the volume slider wasn’t maxed out yet.

So I upped that, and then went back into my sound settings and discovered I had a new option!

Upping the Microphone Boost to just 10 dB give me a huge boost in volume output. Huzzah!

Hopefully someone else with the same problem will find this post useful.

Using OpenGL with Qt: A Tutorial with Code Examples and Screenshots

My last tutorial on this subject was written almost thee years ago, and it’s still the most popular article on this blog, yet I’m not sure even I could follow it. Thus, I’m going through the steps again with the latest versions of NetBeans (7.1.2) and Qt (4.8.1), this time taking screenshots along the way.

Read more Using OpenGL with Qt: A Tutorial with Code Examples and Screenshots

Find where executable is installed to

Often when writing a script, I want to put a hashbang (#!) at the top so that I can execute the file, but I can never remember where the binary for python or php is installed to. An easy way to find out is to use the which command:

mark-ubuntu$ which python
/usr/local/bin/python

Another nice command is whereis which will “locate the binary, source, and manual page files for a command”:

mark-ubuntu$ whereis python
python: /usr/bin/python2.6-config /usr/bin/python2.6 /usr/bin/python /etc/python2.6 /etc/python /usr/lib/python3.1 /usr/lib/python2.6 /usr/local/bin/python2.7-config /usr/local/bin/python2.7 /usr/local/bin/python /usr/local/lib/python2.7 /usr/local/lib/python2.6 /usr/include/python2.6 /usr/share/python /usr/share/man/man1/python.1.gz

JSON Prettifier

This is a simple class I wrote to nicely format a JSON string. Just call it with JsonFormatter.PrettyPrint(yourJsonString)

public static class JsonFormatter
{
    public static string Indent = "    ";

    public static void AppendIndent(StringBuilder sb, int count)
    {
        for (; count > 0; --count) sb.Append(Indent);
    }

    public static bool IsEscaped(StringBuilder sb, int index)
    {
        bool escaped = false;
        while (index > 0 && sb[--index] == '\\') escaped = !escaped;
        return escaped;
    }

    public static string PrettyPrint(string input)
    {
        var output = new StringBuilder(input.Length * 2);
        char? quote = null;
        int depth = 0;

        for(int i=0; i<input.Length; ++i)
        {
            char ch = input[i];

            switch (ch)
            {
                case '{':
                case '[':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        AppendIndent(output, ++depth);
                    }
                    break;
                case '}':
                case ']':
                    if (quote.HasValue)  
                        output.Append(ch);
                    else
                    {
                        output.AppendLine();
                        AppendIndent(output, --depth);
                        output.Append(ch);
                    }
                    break;
                case '"':
                case '\'':
                    output.Append(ch);
                    if (quote.HasValue)
                    {
                        if (!IsEscaped(output, i))
                            quote = null;
                    }
                    else quote = ch;
                    break;
                case ',':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        AppendIndent(output, depth);
                    }
                    break;
                case ':':
                    if (quote.HasValue) output.Append(ch);
                    else output.Append(" : ");
                    break;
                default:
                    if (quote.HasValue || !char.IsWhiteSpace(ch))
                        output.Append(ch);
                    break;
            }
        }

        return output.ToString();
    }
}
Posted in

Subtracting Sets

A couple times now I’ve wanted to subtract one set (`HashSet`) from another. `HashSet` has a method ExceptWith that does just this, except that it modifies the current set in place. What if you don’t want that? You need to copy it first.

Or you could use Linq’s Except method, except that it returns `IEnumerable` instead of a `HashSet`. What if you don’t want that? You need to convert it.

So… which method is faster? Let’s find out!

static class Program
{
    public static HashSet<T> ToSet<T>(this IEnumerable<T> collection)
    {
        return new HashSet<T>(collection);
    }

    public static HashSet<T> Subtract<T>(this HashSet<T> set, IEnumerable<T> other)
    {
        var clone = set.ToSet();
        clone.ExceptWith(other);
        return clone;
    }

    static void Main(string[] args)
    {
        var A = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var B = new HashSet<int> { 2, 4, 6, 8, 10 };
        var sw = new Stopwatch();

        sw.Restart();
        for (int i = 0; i < 1000000; ++i)
        {
            var C = A.Except(B).ToSet();
        }
        sw.Stop();
        Console.WriteLine("Linq: {0} ms", sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < 1000000; ++i)
        {
            var C = A.Subtract(B);
        }
        sw.Stop();
        Console.WriteLine("Native: {0} ms", sw.ElapsedMilliseconds);

        Console.ReadLine();
    }
}

On my computer, this outputs:

Linq: 1291 ms
Native: 756 ms

So, clearly the second method is faster. About 40% for you math types.

I should note that “clone” isn’t really a clone, it’s a shallow copy. Only the container class itself is “cloned”; the elements still refer their originals.

Posted in

String Slice

Here’s an extension method to slice strings in C#, similar to Python’s slice notation.

public static string Slice(this string str, int? start = null, int? end = null, int step = 1)
{
    if (step == 0) throw new ArgumentException("Step size cannot be zero.", "step");

    if (start == null) start = step > 0 ? 0 : str.Length - 1;
    else if (start < 0) start = start < -str.Length ? 0 : str.Length + start;
    else if (start > str.Length) start = str.Length;

    if (end == null) end = step > 0 ? str.Length : -1;
    else if (end < 0) end = end < -str.Length ? 0 : str.Length + end;
    else if (end > str.Length) end = str.Length;

    if (start == end || start < end && step < 0 || start > end && step > 0) return "";
    if (start < end && step == 1) return str.Substring(start.Value, (end - start).Value);

    var sb = new StringBuilder((int)Math.Ceiling((end - start).Value / (float)step));
    for (int i = start.Value; step > 0 && i < end || step < 0 && i > end; i += step)
        sb.Append(str[i]);
    return sb.ToString();
}

"Hello World".Slice(1, -1); // ello Worl
"Hello World".Slice(null, null, -1); // dlroW olleH
Posted in

How to deep-copy/clone an object

The easiest way to deep copy an object is to serialize and deserialize it. Here’s an example from a project I’m working on:

[Serializable()]
public class Board :ICloneable, ISerializable {

    // ...

    object ICloneable.Clone()
    {
        return this.Clone();
    }

    public Board Clone()
    {
        using (var ms = new MemoryStream())
        {
            var bf = new BinaryFormatter();
            bf.Serialize(ms, this);
            ms.Position = 0;
            return (Board)bf.Deserialize(ms);
        }
    }

You might need to implement the serialization functions too for this to work, however.

Posted in