locked
No Binary Format Output? RRS feed

  • Question

  • C# and .NET provide a means of declaring and inputting a binary number, as in 0b_1001_0110, but there appears to be no defined numeric format for outputting a binary value.  One can output a hexadecimal value, as "1000:x8", but there is no "1000:b8" or something similar for outputting binary numbers.  Looks like another format that has to be user-written.
    Monday, August 31, 2020 10:29 PM

Answers

  • I know about hex and octal and binary.  Sometimes you want to see output in pure binary (1's and 0's).  Anyway, I've written some extension methods to format binary and hexadecimal with underscore characters, as well as to format the fractional part of float, double, and decimal numbers with underscore characters for better readability.  Here is the class and the methods.

        /// <summary>
        /// A class to implement extension methods.
        /// </summary>
        public static class ExtensionMethods
        {
            /// <summary>
            /// An extension method to convert a binary number to a string
            /// with underscore ('_') characters separating every 4th group.
            /// </summary>
            /// <param name="binary">A binary number</param>
            /// <returns>A binary formatted string with underscores every 4th group</returns>
            public static string UnderscoreBinaryString (this int binary)
            {
                string binaryString = Convert.ToString (binary,2);
                int    stringLength = binaryString.Length;
    
                var    paddedString    = binaryString.PadLeft (stringLength + 4 - stringLength % 4,'0');
                var    separatedString = new StringBuilder ();
    
                for (int i = 0; i < paddedString.Length; i += 4)
                {
                    separatedString.Append (paddedString.Substring (i,4));
    
                    if (i + 4 < paddedString.Length)
                        separatedString.Append ('_');
                }
    
                return separatedString.ToString ();
    
            } // method UnderscoreBinaryString
    
            /// <summary>
            /// An extension method to convert a hexadecimal number to a string
            /// with underscore ('_') characters separating every group of 4.
            /// </summary>
            /// <param name="hex">A hexadecimal number</param>
            /// <param name="fourGroups">Number of 4-digit groups</param>
            /// <returns>A hexadecimal formatted string with underscores every 4th digit</returns>
            public static string UnderscoreHexString (this int hex, int fourGroups)
            {
                int    width       = 4 * fourGroups;
                string formatWidth = width.ToString ();
                string hexString   = string.Format ("{0:x}" + formatWidth,hex);
                int    stringLength = hexString.Length;
    
                var    paddedString    = hexString.PadLeft (stringLength + 4 - stringLength % 4,'0');
                var    separatedString = new StringBuilder ();            
    
                for (int i = 0; i < paddedString.Length; i += 4)
                {
                    separatedString.Append (paddedString.Substring (i,4));
    
                    if (i + 4 < paddedString.Length)
                        separatedString.Append ('_');
                }
    
                return separatedString.ToString ();
    
            } // method UnderscoreHexString
    
            /// <summary>
            /// An extension method to format the fraction part of a number
            /// with underscores ('_') everything three characters.
            /// </summary>
            /// <typeparam name="T">Type of the number (float, double, decimal)</typeparam>
            /// <param name="value">The number to be formatted</param>
            /// <returns>The formatted string</returns>
            public static string UnderscoreFractionalPartOfNumber<T> (this T value)
            {
                if (value.GetType().Equals (typeof (double)) ||
                    value.GetType().Equals (typeof (float))  ||
                    value.GetType().Equals (typeof (decimal)))
                {
                    String[] stringArray = value.ToString ().Split ('.');
                
                    var wholePart = string.Format ("{0:N0}",stringArray[0]);
                    int substringLength;
    
                    if (stringArray.Length > 1)
                    {
                        var fractionPart = stringArray[1];
    
                        int fractionLength = fractionPart.Length;
    
                        var separatedString = new StringBuilder ();
    
                        for (int i = 0; i < fractionLength; i += 3)
                        {
                            substringLength = fractionPart.Substring (i).Length;
    
                            separatedString.Append (fractionPart.Substring (i,substringLength < 3 ? substringLength : 3));
    
                            if (i + 3 < fractionLength)
                                separatedString.Append ('_');
                        }
    
                        return wholePart + "." + separatedString.ToString ();
    
                    }
                    else
                        return wholePart;
                }
                else
                    throw new ArgumentException ("Value must be of type float, double, or decimal only.");
            } // method UnderscoreFractionalPartOfNumber
        } // class ExtensionMethods
    

    Tuesday, September 1, 2020 6:35 PM

All replies

  • C# and .NET provide a means of declaring and inputting a binary number, as in 0b_1001_0110, but there appears to be no defined numeric format for outputting a binary value.  One can output a hexadecimal value, as "1000:x8", but there is no "1000:b8" or something similar for outputting binary numbers.  Looks like another format that has to be user-written.

    Hexadecimal is the Base-16 number system invented solely for representing binary values.  Each (individual) alpha-numeric hex digit represents 4 bits precisely.

    0x0 == 0000
    0x1 == 0001
    0x2 == 0010
    0x3 == 0011
    0x4 == 0100
    0x5 == 0101
    0x6 == 0110
    0x7 == 0111
    0x8 == 1000
    0x9 == 1001
    0xA == 1010
    0xB == 1011
    0xC == 1100
    0xD == 1101
    0xE == 1110
    0xF == 1111
    

    That's why hexadecimal is Base-16. It's for representing binary values.

    Is there any particular reason why hex doesn't work for you?


    Before you can learn anything new you have to learn that there's stuff you don't know.

    Monday, August 31, 2020 10:57 PM
  • It may need to be user-written, but that's just a 2-part call so it rarely matters to me.

    Console.WriteLine(Convert.ToString(1234,2).PadLeft(8, '0'));

    string input = "10011010010";
    Console.WriteLine(Convert.ToInt32(input, 2));

    EDIT: I use 8 character padding because it's shown in the question you want it to have length 8 (':b8'), however to do it right it should be padded to 32-character long as integer in C# is 32-bit in size.


    Tuesday, September 1, 2020 1:34 AM
    Answerer
  • I know about hex and octal and binary.  Sometimes you want to see output in pure binary (1's and 0's).  Anyway, I've written some extension methods to format binary and hexadecimal with underscore characters, as well as to format the fractional part of float, double, and decimal numbers with underscore characters for better readability.  Here is the class and the methods.

        /// <summary>
        /// A class to implement extension methods.
        /// </summary>
        public static class ExtensionMethods
        {
            /// <summary>
            /// An extension method to convert a binary number to a string
            /// with underscore ('_') characters separating every 4th group.
            /// </summary>
            /// <param name="binary">A binary number</param>
            /// <returns>A binary formatted string with underscores every 4th group</returns>
            public static string UnderscoreBinaryString (this int binary)
            {
                string binaryString = Convert.ToString (binary,2);
                int    stringLength = binaryString.Length;
    
                var    paddedString    = binaryString.PadLeft (stringLength + 4 - stringLength % 4,'0');
                var    separatedString = new StringBuilder ();
    
                for (int i = 0; i < paddedString.Length; i += 4)
                {
                    separatedString.Append (paddedString.Substring (i,4));
    
                    if (i + 4 < paddedString.Length)
                        separatedString.Append ('_');
                }
    
                return separatedString.ToString ();
    
            } // method UnderscoreBinaryString
    
            /// <summary>
            /// An extension method to convert a hexadecimal number to a string
            /// with underscore ('_') characters separating every group of 4.
            /// </summary>
            /// <param name="hex">A hexadecimal number</param>
            /// <param name="fourGroups">Number of 4-digit groups</param>
            /// <returns>A hexadecimal formatted string with underscores every 4th digit</returns>
            public static string UnderscoreHexString (this int hex, int fourGroups)
            {
                int    width       = 4 * fourGroups;
                string formatWidth = width.ToString ();
                string hexString   = string.Format ("{0:x}" + formatWidth,hex);
                int    stringLength = hexString.Length;
    
                var    paddedString    = hexString.PadLeft (stringLength + 4 - stringLength % 4,'0');
                var    separatedString = new StringBuilder ();            
    
                for (int i = 0; i < paddedString.Length; i += 4)
                {
                    separatedString.Append (paddedString.Substring (i,4));
    
                    if (i + 4 < paddedString.Length)
                        separatedString.Append ('_');
                }
    
                return separatedString.ToString ();
    
            } // method UnderscoreHexString
    
            /// <summary>
            /// An extension method to format the fraction part of a number
            /// with underscores ('_') everything three characters.
            /// </summary>
            /// <typeparam name="T">Type of the number (float, double, decimal)</typeparam>
            /// <param name="value">The number to be formatted</param>
            /// <returns>The formatted string</returns>
            public static string UnderscoreFractionalPartOfNumber<T> (this T value)
            {
                if (value.GetType().Equals (typeof (double)) ||
                    value.GetType().Equals (typeof (float))  ||
                    value.GetType().Equals (typeof (decimal)))
                {
                    String[] stringArray = value.ToString ().Split ('.');
                
                    var wholePart = string.Format ("{0:N0}",stringArray[0]);
                    int substringLength;
    
                    if (stringArray.Length > 1)
                    {
                        var fractionPart = stringArray[1];
    
                        int fractionLength = fractionPart.Length;
    
                        var separatedString = new StringBuilder ();
    
                        for (int i = 0; i < fractionLength; i += 3)
                        {
                            substringLength = fractionPart.Substring (i).Length;
    
                            separatedString.Append (fractionPart.Substring (i,substringLength < 3 ? substringLength : 3));
    
                            if (i + 3 < fractionLength)
                                separatedString.Append ('_');
                        }
    
                        return wholePart + "." + separatedString.ToString ();
    
                    }
                    else
                        return wholePart;
                }
                else
                    throw new ArgumentException ("Value must be of type float, double, or decimal only.");
            } // method UnderscoreFractionalPartOfNumber
        } // class ExtensionMethods
    

    Tuesday, September 1, 2020 6:35 PM
  • Hi MesPia,

    It seems that your problem has been solved, so please click the "Mark as Answer" Link at the bottom of the correct post(s), so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, September 2, 2020 2:16 AM