Search This Blog

Monday, August 1, 2016

.NET's built in methods to convert between distinct numeric representations (supports 2, 8, 10 and 16 only)

Here's something that few seem to know about, but that more than often we are in need of: the .NET's Convert methods can convert to/from the following numeric representations 2, 8, 10, 16.

            var binary = Convert.ToString(30, 2); // 11110
            var bits = binary.ToCharArray().Select(c => byte.Parse(c.ToString())); // a collection of the bits stored in 'binary' above
            var hexa = Convert.ToString(100, 16); //64
            var octa = Convert.ToInt64(12.ToString(), 8); //10 (decimal representation of 12 in base 8 = 10)

No comments:

Post a Comment